I would like to add a basic click handler to an element using ID. Normally I would use jQuery, but I have forgotten how to do it in vanilla js.
What is the best way to do this, without using jQuery:
$("#myBasic").click(function(){
alert(“testString”);
});
Very basic way is to just assign a function to the
on[event]property of the elementThis has very broad browswer support, and is useful for most basic cases
There are other event handling features as well, like
.addEventListener(evt, fn, capture), but IE only started supporting it in IE9. Before that, you’d need to useattachEvent(onevt, fn), which is similar, but not identical.The main trouble with
.attachEvent()is that it doesn’t give you an automatic reference to the element that bound the handler viathis. But there are workarounds for that.To create a fairly browser compatible solution, you could do something like this:
And you’d call it like this:
This should cover most situations, though I’d be a little concerned about memory leaks for the
.attachEventversion.All this only deals with binding the handler. To obtain consistent cross-browser behavior, you’d likely need to have a fix ready for the
eventobject.