Created
October 30, 2012 20:59
-
-
Save bjankord/3983019 to your computer and use it in GitHub Desktop.
Cross-Browser Debounce Resize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Tested in: | |
Chrome - 22 : Works | |
FF - 16 : Works | |
IE - 10 | |
IE - 9 : Works | |
IE - 8 : no alert - check at home | |
IE - 7 : no alert - "" | |
IE - 6 : posts alert twice | |
Opera - : Works | |
Safari - : Works | |
iPad | |
iPad Mini | |
iPhone | |
iPod | |
Android Tablet | |
Android Phone | |
Blackberry Phone | |
BB Playbook | |
Surface | |
Windows Phone 7.5 | |
Windows Phone 8 | |
*/ | |
// Add and Remove Events | |
var event = { | |
add: function(elem, type, fn) { | |
if (elem.attachEvent) { | |
elem['e'+type+fn] = fn; | |
elem[type+fn] = function() {elem['e'+type+fn](window.event);} | |
elem.attachEvent('on'+type, elem[type+fn]); | |
} else | |
elem.addEventListener(type, fn, false); | |
}, | |
remove: function(elem,type,fn) { | |
if (elem.detachEvent) { | |
elem.detachEvent('on'+type, elem[type+fn]); | |
elem[type+fn] = null; | |
} else | |
elem.removeEventListener(type, fn, false); | |
} | |
} | |
// Debounce Function - http://davidwalsh.name/function-debounce | |
var debounce = function(func, wait, immediate) { | |
var timeout; | |
return function() { | |
var context = this, args = arguments; | |
var later = function() { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
var callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
}; | |
var logTest = function() { | |
//console.log("test"); | |
alert("test"); | |
} | |
// Run when DOM is ready | |
logTest(); | |
// Debounce on resize | |
var logTestDB = debounce(function(e) { | |
logTest(); | |
}, 500); // Maximum run of once per 500 milliseconds | |
// Run on resize | |
event.add(window, "resize", logTestDB); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment