Reputation: 51
I use Paul Irish Smartresize but when I resize the window the function inside resize() fires multiple times causing my accordion not to work properly. Does anyone have any idea why this happens? Here is the code running: http://jsfiddle.net/rebel2000/PnAH7/6/
$(document).ready( function(){
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
function anim3() {
$('#button').click(
function(){
if($(this).hasClass('active')){
$(this).animate({ "height": "30px"}, { queue:true, duration: 900 });
$(this).removeClass('active');
return false;
} else {
$(this).animate({ "height": "100px"}, { queue:true, duration: 900 });
$(this).addClass('active');
return false;
}
}
);
}
//anim3();
$(window).smartresize(function(){
anim3();
});
});
Upvotes: 0
Views: 3871
Reputation: 37177
That happens because when you are re-sizing, the re-size event fires multiple times. Teorically(more for illustration purposes) when the JavaScript loop goes through the verification of the window size it detects it is smaller/larger than before and fires it again. As the loop is very fast you get multiple fires, during your "single" re-size.
You can do something like this:
var idCounter = 0;
$(window).smartresize(function(){
var myId=(++idCounter);
setTimeout(function(){
if(myId===idCounter){
anim3();
}
}, 500); // 500 milli the user most likely wont even notice it
}
This should safely ignore the multiple fires and only process on the last one. (Unless you take lots of time to resize, in that case you can increase the timeout)
Upvotes: 2
Reputation: 4995
Here's a great piece of code that handles this for you :
http://benalman.com/projects/jquery-throttle-debounce-plugin/
Also see:
http://benalman.com/projects/jquery-dotimeout-plugin/
Upvotes: 0