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?
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.
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.
document.getElementById('element').onclick = function(e){ alert('click'); }
DEMO: http://jsfiddle.net/e9jZW/1/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With