Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you catch a click event with plain Javascript?

I know that when using jQuery you can do $('element').click(); to catch the click event of an HTML element, but how do you do that with plain Javascript?

like image 932
chromedude Avatar asked Oct 26 '11 19:10

chromedude


People also ask

How do you add a click event to a button with plain JavaScript?

To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.

How can I trigger a click event in JavaScript?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.


2 Answers

document.getElementById('element').onclick = function(e){   alert('click'); } 

DEMO: http://jsfiddle.net/e9jZW/1/

like image 186
Rocket Hazmat Avatar answered Oct 08 '22 15:10

Rocket Hazmat


By adding an event listener or setting the onclick handler of an element:

var el = document.getElementById("myelement");  el.addEventListener('click', function() {   alert("Clicked"); });  // ... or ...  el.onclick = function() {   alert("Clicked"); } 

Note that the even listener style allows multiple listeners to be added whereas the callback handler style is exclusive (there can be only one).

If you need to add these handlers to multiple elements then you must acquire them as appropriate and add them to each one separately.

like image 27
maerics Avatar answered Oct 08 '22 17:10

maerics