biqpfw
Last Updated: March 02, 2018
·
22.45K
· sk5

Jquery - Window size onload and onresize.

One of the common problems I come across with Responsive Web Design is that I want a button to fire a different series of actions based on the size of the window. In Jquery the underlying problem with that is that $(window).resize is not something that is fired on $(document).ready. In order to have a button fire in both of these instances you need to attach the function to document ready and when you re-size the window.

JQuery

onResize = function() {
    if($(window).width() < 530) {
        $('.button').on('click', function() {
            /* Your code here */
        })
    } else {
        $('.button').off('click');
    }
}

$(document).ready(onResize);
$(window).resize(onResize);

This should allow you to fire a click action if the window size is < 530px. If the browser loads or is re-sized larger than this, the button click will not fire.

Additionally, $(window).resize is know to come with some lag. To make up for this you can add a function for delaying repeated actions. At the top of your code you can add the following code...

var delay = (function() {
    var timer = 0;
    return function(callback, ms){
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    }
})();

Now that you have a function to handle the delayed actions you will want to edit your $(window).resize to respond accordingly.

$(window).resize(function() {
    delay(function(){
        onResize();
    },100)
});

Now you have a button that acts differently based on window size, and has no lag after the window has been re-sized.