Jacob Jacob - 1 day ago 5
HTML Question

Disable Jquery Based on Screen Size

I would like to disable the following javascript if a screen size is < 601px:

$(function() {
function rotate() {
$('#homemaincontent div').last().fadeOut(2000, function() {
$(this).insertBefore($('#homemaincontent div').first()).show();
});
}
setInterval(function() {
rotate();
}, 7000);
});


I found the following page with what seemed like a good answer, but I can't get it work:

Disable jquery function when screen width larger than 480

Any help you can provide would be much appreciated!

Answer
$(function() {
  function rotate() {
    $('#homemaincontent div').last().fadeOut(2000, function() {
      $(this).insertBefore($('#homemaincontent div').first()).show();
    });
   }
     setInterval(function() {
         if(Math.max(document.documentElement.clientWidth, window.innerWidth || 0) > 601)
             rotate();
     }, 7000);
    });

so now each time rotate is called it will first check if the viewport width is more than 601 and if it is it will execute the function.

If you dont want to adjust for responsive behaviour you can just put that if statement to run at the begining of $(function(){ insert if () run rest of code else do nothing}and it will only evaluate once when your script runs for the first time

EDIT To answer about your 2nd question in the comment

Create a staticImageX css class and a DynamicImageX class that will have the needed css like position, width, top etc. Use jquery and the above expression to test against the width again and run jquery code to adjust the class on the image container on the same intervan as your rotate function So

if(width > 601)
    $('#imageContainer').addClass('DynamicImageX').removeClass('staticImageX')
else 
    $('#imageContainer').addClass('staticImageX').removeClass('DynamicImageX')** 
Comments