Javascript mobile device width check and class remove

832 views Asked by At

I need to remove some classes from my site if the device width is under 1200 px (because of the mobile view).

I tried to use Javascript, this method worked fine:

$(window).resize(function(){
var current_width = $(window).width();
if(current_width < 1200)
  $('a').removeClass("expand");
  $( ".effects clearfix" ).remove();
  $( ".overlay" ).remove();
  $('#removeimg').removeClass('img').addClass('imgmobile');}); 

But the problem is, this works only if I resize the window. So if I open the site using my smartphone (Android 4.3, Chrome) the script does not work.

I tried to write this code but I failed:

function checkWidth() {
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    if (window.innerWidth < 1200)  {
        $('#removeimg').removeClass('img').addClass('imgmobile');     
    }
    if (window.innerWidth < 1200) {
        $( ".effects clearfix" ).remove();    
    }
    if (window.innerWidth < 1200) {
        $( ".overlay" ).remove();    
    }
    if (window.innerWidth < 1200) {
        $('a').removeClass("expand");  
    }

How can I check the device width and set these classes under 1200 px? (I also tried to modify/set initial values/ the css with media queries but unfortunately I still need to remove the classes :( )

Thank you for any idea.

3

There are 3 answers

1
byrdr On

Try wrapping the window in a jquery element. That should work for you. You'll also need an event to trigger this function.

$(document).ready(function(){
   if ($(window).innerWidth() < 1200)  {
            $('#removeimg').removeClass('img').addClass('imgmobile');     
        }
});
0
Sahil Gupta On

You had placed code inside resize function, that's it's only working on resize of window. Call in once in ready function and once in resize too.

1
Csteele5 On

Another solution might be to use separate classes and use display: show and display: hide in a media query in the CSS.

This works well across mobile platforms, but you may have to do multiple media queries. I hope this helps.