Created
November 2, 2017 21:42
-
-
Save banhaclong20/11353a302c2458d34c8d128d7f77a937 to your computer and use it in GitHub Desktop.
Create dispatchEvent Vanilla JS
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
// Markup | |
<input type="checkbox" id="checkbox"/><label for="checkbox">Checkbox</label> | |
Simulate click <input type="button" onclick="simulateClick();" value="Simulate click"/> | |
Add a click handler that calls preventDefault <input type="button" onclick="addHandler();" value="Add a click handler that calls preventDefault"/> | |
Remove the click handler that calls preventDefault <input type="button" onclick="removeHandler();" value="Remove the click handler that calls preventDefault"/> | |
// Script | |
var checkbox = document.querySelector('.checkbox') | |
function preventDef(event) { | |
event.preventDefault(); | |
}; | |
function addHandler() { | |
checkbox.addEventListener('click', preventDef, false); | |
}; | |
function removeHandler() { | |
checkbox.removeEventListener('click', preventDef, false); | |
}; | |
function simulateClick() { | |
var event = new MouseEvent('click', { | |
view: window, | |
bubbles: true, | |
cancelable: true | |
}); | |
var cb = document.getElementById('checkbox'); | |
var cancelled = !cb.dispatchEvent(event); | |
if (cancelled) { | |
// A handler called preventDefault. | |
alert("cancelled"); | |
} else { | |
// None of the handlers called preventDefault. | |
alert("not cancelled"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment