I'm little confusing by using "onclick" "onmousedown" as a property of HTML elements.
Such as:
<button onclick="my_JS_function()"></button>
or
<div onmousedown="my_another_JS_funciton"></div>
But some people tell that only "proper" way of adding "listeners" are by
document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);
What is the more "proper" more supported way of doing that?
addEventListener() has multiple advantages: Allows you to register unlimited events handlers and remove them with element. removeEventListener() . Has useCapture parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase.
The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.
if you already know function and element is part of html i.e. not get added dynamically than its good that you add function inline rather than using extra method call like "addEventListener"
Another thing to note
While onclick works in all browsers, addEventListener does not work in older versions of Internet Explorer, which uses attachEvent instead.
OnClick is a DOM Level 0 property. AddEventListener is part of the DOM Level 2 definition. Read about this : http://www.w3.org/TR/DOM-Level-2-Events/events.html
inline event handlers added as HTML tag attributes, for example:
<a href="gothere.htm" onlick="alert('Bye!')">Click me!</a>
The above techniques are simple but have certain disadvantages: they allow you to have just one event handler per element. In addition, with inline event handlers you get very poor separation of JavaScript code from HTML markup.
document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);
Advatange of this : you can add multiple event handler. also separte html and javascript code
For more detail you can read this : Adding an Event Handler
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