Skip to content

Instantly share code, notes, and snippets.

@SaraSoueidan
Created September 7, 2018 07:18
Show Gist options
  • Save SaraSoueidan/b13113cd0bb6534808a41705eed4b4ad to your computer and use it in GitHub Desktop.
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/
/**
* 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