Last active
January 17, 2024 12:43
-
-
Save abhijitmamarde/61b105d014677e592ee11958bde2805e to your computer and use it in GitHub Desktop.
To send click event to a element on plain 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
function eventFire(el, etype){ | |
if (el.fireEvent) { | |
el.fireEvent('on' + etype); | |
} else { | |
var evObj = document.createEvent('Events'); | |
evObj.initEvent(etype, true, false); | |
el.dispatchEvent(evObj); | |
} | |
} | |
/* | |
Usage: | |
<button id="the_id">Click Me</button> | |
e = document.getElementById("the_id"); | |
eventFire(e, "click"); | |
*/ | |
// ========== OR ============ | |
var elem = document.getElementById('the_id'); | |
// Simulate clicking on the specified element. | |
triggerEvent( elem, 'click' ); | |
/** | |
* Trigger the specified event on the specified element. | |
* @param {Object} elem the target element. | |
* @param {String} event the type of the event (e.g. 'click'). | |
*/ | |
function triggerEvent( elem, event ) { | |
var clickEvent = new Event( event ); // Create the event. | |
elem.dispatchEvent( clickEvent ); // Dispatch the event. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment