Cross-browser function to remove events from DOM elements.
Last active
December 17, 2015 00:29
-
-
Save dciccale/5521707 to your computer and use it in GitHub Desktop.
Cross-browser removeEvent function done with 84 bytes of JavaScript
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
<!doctype html> | |
<title>Demo</title> | |
<span id="btn">Button</span> | |
<script> | |
// use addEvent cross-browser shim: https://gist.github.com/dciccale/5394590/ | |
var addEvent = function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}}; | |
// removeEvent | |
var removeEvent = function(a,b,c){try{a.removeEventListener(b,c,!1)}catch(d){a.detachEvent('on'+b,c)}}; | |
// DOM element | |
var element = document.getElementById('btn'); | |
// callback function | |
var callback = function () { alert('Button clicked!'); }; | |
// alert 'Button clicked!' when clicked | |
addEvent(element, 'click', callback); | |
// remove the 'click' event | |
removeEvent(element, 'click', callback); | |
</script> |
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
/** | |
* @param element The element to remove the event from | |
* @param type Event type (i.e. 'click') | |
* @param callback Original function that was attached to the specified event | |
*/ | |
function (element, type, callback) { | |
try { | |
element.removeEventListener(type, calback, false); | |
} catch (e) { | |
element.detachEvent('on' + type, callback); | |
} | |
}; |
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
function(a,b,c){try{a.removeEventListener(b,c,!1)}catch(d){a.detachEvent('on'+b,c)}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment