Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before after resize event

Tags:

jquery

resize

I would like to do something before and after resizing element, i have tried to bind resize event and it work:

$('#test_div').bind('resize', function(){
            // do something
});

I have found some questions, but the solutions are timeout, i don't want to use timeout. I would just like to process immediately :)

See also:

  • JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

  • jQuery - how to wait for the 'end' or 'resize' event and only then perform an action?

Thank for any suggestions :)

like image 597
Rong Nguyen Avatar asked Dec 15 '22 10:12

Rong Nguyen


2 Answers

There is no such thing as a resize end event that you can listen to. The only way to know when the user is done resizing is to wait until some short amount of time passes with no more resize events coming. That's why the solution nearly always involves using a setTimeout() because that's the best way to know when some period of time has passed with no more resize events.

This previous answer of mine listens for the .scroll() event, but it's the exact same concept as .resize(): More efficient way to handle $(window).scroll functions in jquery? and you could use the same concept for resize like this:

var resizeTimer;
$(window).resize(function () {
    if (resizeTimer) {
        clearTimeout(resizeTimer);   // clear any previous pending timer
    }
     // set new timer
    resizeTimer = setTimeout(function() {
        resizeTimer = null;
        // put your resize logic here and it will only be called when 
        // there's been a pause in resize events
    }, 500);  
}

You can experiment with the 500 value for the timer to see how you like it. The smaller the number, the more quickly it calls your resize handler, but then it may get called multiple times. The larger the number, the longer pause it has before firing, but it's less likely to fire multiple times during the same user action.

If you want to do something before a resize, then you will have to call a function on the first resize event that you get and then not call that function again during the current resize operation.

var resizeTimer;
$(window).resize(function () {
    if (resizeTimer) {
        clearTimeout(resizeTimer);   // clear any previous pending timer
    } else {
        // must be first resize event in a series
    }
     // set new timer
    resizeTimer = setTimeout(function() {
        resizeTimer = null;
        // put your resize logic here and it will only be called when 
        // there's been a pause in resize events
    }, 500);  
}
like image 161
jfriend00 Avatar answered Dec 28 '22 08:12

jfriend00


You could use the smart resize jQuery plugin but in the end it still uses setTimeout().

Then again, it won't wait for the end of the resize... it just throttles it.

like image 40
VVV Avatar answered Dec 28 '22 09:12

VVV