As a beginner I was just experimenting with various HTML elements and scripts. I then came across the HTML attribute onclick.
As I had done more of scripting before my experiments with HTML, I was wondering if there is any difference between calling the function via the DOM itself or through JS/Jquery's event listener.
E.g:-
<button onclick="myFunc()" id="btn1">button 1</button>
<button id="btn2">button 2</button>
<script>
$(document).on('click','#btn2",function(){
//code here
});
</script>
I would also like to know the pros and cons and which of the two is best practice.
Please do let me know if I am breaking the rules of asking questions here so I could modify/delete the question.
I would also like to know the pros and cons and which of the two is best practice.
Pros of "VS Script":
onClick
or similar attribute is a mix of JS within the HTML - this goes against the Separation of Concerns principle. With the "VS Script" the logic is separate from the markup.onclick
, onmouseout
, etc.Cons of "VS Script":
For a more detailed explanation, see this answer.