jQuery set the click event the right way

Everybody should know multiple ways how to set click events in JavaScript and jQuery. But if there are multiple different ways which one is the right one?

First of all what ways do we have?

There are the declaratively ways:

1
2
3
4
5
<!-- declaratively example one -->
<a href="javascript:myFunction()">click me</a>

<!-- declaratively example two -->
<button onclick="myFunction()">Click me</button>
And the programaticaly way:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// the JavaScript way
document.getElementById("elementID").onclick = function() {              
   alert("hello");          
};

// jQuery way one
$("#elementID").click(function(){
   alert("hello");  
});

// jQuery way two
$('#elementID').on("click", function() {
   alert("hello");  
});

So in my opinion the programaticaly ways are always the best ways for a simple reason: the code is easier to read.
Usualy you have at least two files (the HTML file and the JavaScript file). If you are setting the click declaratively it is set in the HTML file, but the function itself is in the JavaScript file. So this is not easy to read if you are opening the JavaScript and you see a function and you do not know where an when it is called.

So know the question we are talking about: What should I use?
Of course the jQuery way is always the nicest, but there are two. Well, way one is the way you should do it if the element you are giving the click event was created by DOM. If you have a dynamic created element you should use way two.

Comments

Popular posts from this blog

How to support multiple languages in WPF