Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save banhaclong20/11353a302c2458d34c8d128d7f77a937 to your computer and use it in GitHub Desktop.
Save banhaclong20/11353a302c2458d34c8d128d7f77a937 to your computer and use it in GitHub Desktop.
Create dispatchEvent Vanilla JS
// 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