Created
September 7, 2018 07:18
-
-
Save SaraSoueidan/b13113cd0bb6534808a41705eed4b4ad to your computer and use it in GitHub Desktop.
Vanilla JS .click() doesn't apply to links <a>, so this is a function that enables it to work on them. Source: https://gomakethings.com/how-to-simulate-a-click-event-with-javascript/
This file contains hidden or 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
/** | |
* Simulate a click event. | |
* @public | |
* @param {Element} elem the element to simulate a click on | |
*/ | |
var simulateClick = function (elem) { | |
// Create our event (with options) | |
var evt = new MouseEvent('click', { | |
bubbles: true, | |
cancelable: true, | |
view: window | |
}); | |
// If cancelled, don't dispatch our event | |
var canceled = !elem.dispatchEvent(evt); | |
}; | |
// To use it, call the function, passing in the element you want to simulate the click on. | |
var someLink = document.querySelector('a'); | |
simulateClick(someLink); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment