I have a button in html:
<button id="MyButton" onclick="return DoSomething()">Click Me</button>
Is it better to put the "onclick" property in the html or use javascript/DOM to attach a callback to the button click?
To call a JavaScript function from a button click, you need to add an event handler and listen for the click event from your <button> element. You can the id attribute to the <button> so that you can fetch it using the document. getElementById() method.
JavaScript – Call Function on Button Click Get the reference to the button. For example, using getElementById() method. Call addEventListener() function on the button with the “click” action and function passed as arguments.
Use the onclick attribute to execute a script when the element is clicked in HTML.
It's considered better to attach it via JavaScript. This falls under the category of "Unobtrusive JavaScript". (more specifically here the separation of behavior from the layout)
document.getElementById('YourID').onclick = nameOfFunctionToBeCalled;
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