Click Me Is it...">

Link button with 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 html or use javascript / DOM to attach a callback to a button click?

+3
source share
5 answers

It was believed that it was better to attach it via JavaScript. This is categorized as " Unobtrusive JavaScript ." (more specifically here is the separation of behavior from the layout)

document.getElementById('YourID').onclick = nameOfFunctionToBeCalled;
+7
source

Favorable separation of representation and logic, I suggest that you associate events with it through Javascript:

document.getElementById("MyButton").onclick = function(){
  alert("Button Clicked");
}

Javascript CSS HTML, . Javascript . ( javascript).

+3

jQuery click()

$('#MyButton').click(DoSomething);
+2

Javascript . .js , JS- HTML.

raw DOM :

document.getElementById( "MyButton" ).onclick = DoSomething;
+2

I use an event ondomreadyto assign all of my events, usually waterless in a separate script. All my logic is in one place, and my markup looks a lot neater. I am of the opinion that markup is simply intended to describe the initial structure of the page. The code lives in the code file, and the styles belong in the css file.

+1
source

Source: https://habr.com/ru/post/1733053/


All Articles