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();
});
});
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:
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)