Reputation: 3
Jquery bind allows to dynamically bind events to html elements. Other than that, let's say if I have a function to be called every time a checkbox value is changed, is there any advantage of binding the function using jquery on("change") compared to directly adding the onchange attribute to the html element in the jsp?
Upvotes: 0
Views: 93
Reputation: 25351
Some people like to follow the separation patterns very strictly and they consider JavaScript to be functionality while HTML is obviously presentation, so they like to separate the functionality from presentation and the jQuery way offers you that.
I personally prefer to leave it in the HTML unless I need to bind it at run-time for some reason.
Of course there are some cases where you need to use the jQuery way other than just the need to bind the event at run-time. For instance, if you want to bind more than one function to the same event. However, most of those cases can still be done in the HTML way (you call one function that in turn calls as many functions as you want).
One tiny benefit for the jQuery way is the this
keyword. In jQuery bound events, this
conveniently refers to the element that owns the event. In HTML, this
sadly refers to the window
object, so if you want a reference to the element, you will need to pass this
to the function <input type="button" onclick="myFunction(this);">
.
Upvotes: 1