I know this is easily done in jQuery or any other framework, but that's not really the point. How do I go about 'properly' binding a click event in pure javascript? I know how to do it inline (I know this is terrible)
<a href="doc.html" onclick="myFunc(); return false">click here</a>
and this causes my javascript to execute for a JS enabled browser, and the link to behave normally for those without javascript?
Now, how do I do the same thing in a non-inline manner?
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.
bind() method is used for attaching an event handler directly to elements.
If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
If you need to assign only one click
event, you can assign onclick
:
If you have an ID:
myAnchor = document.getElementById("Anchor");
myAnchor.onclick = function() { myFunc(); return false; }
you can also walk through all anchors:
anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].onclick = .....
}
There's also a document.getElementsByClassName
to simulate jQuery's class selector but it is not supported by all browsers.
If it could be that you need to assign multiple events on one element, go with addEventListener
shown by @Jordan and @David Dorward.
The basic way is to use document.getElementById()
to find the element and then use addEventListener
to listen for the event.
In your HTML:
<a href="doc.html" id="some-id">click here</a>
In your JavaScript:
function myFunc(eventObj) {
// ...
}
var myElement = document.getElementById('some-id');
myElement.addEventListener('click', myFunc);
Or you can use an anonymous function:
document.getElementById('some-id').addEventListener('click', function(eventObj) {
// ...
});
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