Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Window resize; after

I am currently using jQuery's resize function, but because of what I adjust on resize, there's simply too much going on to make it look smooth, as it fires at every adjustment.

$(window).resize(function() {

myFunction();

});

Is there a way to fire a function off after the resize has stopped? Like $(window).afterResize() or something?

Any solutions welcome.

like image 251
Michael Giovanni Pumo Avatar asked Jan 19 '23 18:01

Michael Giovanni Pumo


2 Answers

Set a timeout and do the action 100ms later, perhaps.

var timer;
$(window).resize(function() {
    clearTimeout(timer);
    timer = setTimeout(myFunction, 100);
});
like image 101
lonesomeday Avatar answered Jan 28 '23 15:01

lonesomeday


I am not sure if there is a 'clean' native way to do it (hopefully there is and someone will shed light)

but you "hack" it like this http://jsfiddle.net/tuuN3/

var myInterval = false; // this variable will hold the interval and work as a flag
var $win = $(window); //jquery win object
var dimensions = [ $win.width(), $win.height() ]; //initial dimensions

$(window).resize(function() { //on window resize...

    if( !myInterval ) //if the interval is not set,
    {
        myInterval  = setInterval( function() { //initialize it
            //and check to see if the dimenions have changed or remained the same
            if( dimensions[ 0 ] === $win.width() && dimensions[ 1 ] ===  $win.height() )
            {   //if they are the same, then we are no longer resizing the window
                clearInterval( myInterval ); //deactivate the interval
                myInterval = false; //use it as a flag

                doStuff(); //call your callback function
            }
            else
            {
                 dimensions[ 0 ] =    $win.width(); //else keep the new dimensions
                 dimensions[ 1 ] =    $win.height();
            }
        }, 64 );  //and perform a check every 64ms
    }

});
like image 45
Pantelis Avatar answered Jan 28 '23 16:01

Pantelis