Search code examples
jqueryresponsive-designscreen-size

jQuery - start script if browser width is more than 960 px


I was using this script so that certain DIVs would appear when scrolled by, but when using a mobile device it doesn't work so well. For instance, when using an iPad, the DIVs whould never show up if I didn't lift my finger from the screen or until the page stopped scrolling.

Here's what I have:

$(document).ready(function()
{
    $(window).scroll( function(){
        $('.hidden').each( function(i){
            var bottom_of_object = $(this).position().top + $(this).outerHeight() / 4;
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            if( bottom_of_window > bottom_of_object ){
                $(this).animate({'opacity':'1'},500);
            }
        }); 
    });
});

Now I just want this script to start if the browser window is larger than 960, in order for it not to work on mobile devices.

Thank you.


Solution

  • Use the .width() function to get the browser's width, and only execute the code if it exceeds 960:

    $(document).ready(function() {
        $(window).scroll(function() {
            if($(window).width() > 960) {
                $('.hidden').each( function(i){
                    var bottom_of_object = $(this).position().top + $(this).outerHeight() / 4;
                    var bottom_of_window = $(window).scrollTop() + $(window).height();
                    if( bottom_of_window > bottom_of_object ){
                        $(this).animate({'opacity':'1'},500);
                    }
                }); 
            }
        });
    });