Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tie a button to a javascript function

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?

like image 459
Robert Avatar asked Feb 16 '10 18:02

Robert


People also ask

How do you call a function with a button?

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.

How do you call a button in JavaScript?

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.

How do you call a script when a button is pressed HTML?

Use the onclick attribute to execute a script when the element is clicked in HTML.


1 Answers

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;
like image 54
RC. Avatar answered Sep 28 '22 13:09

RC.