Preferred Use .on() Method Rather Than .click(), .bind(), .hover(), .load(), .ready(), Etc
I need a better way to achieve the best performance and concise code use event delegation whenever possible. Especially the correct .ready(): $(document).ready(function() or $(d
Solution 1:
From jQuery .ready() docs:
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
$( handler ) $( document ).ready( handler ) $( "document" ).ready( handler ) $( "img" ).ready( handler ) $().ready( handler )
As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.
So the best and shortest way is this:
$(function() {
// your code
});
For .click()
event and its friends it's more complicated.
.click(function(){})
is a shortcut for .on("click", function(){})
so they can be used interchangeably.
However .on()
function has additional feature for creating delegated events.
.on( "click", "selector", function() {});
So if you want concise code stick to the .on()
version.
Post a Comment for "Preferred Use .on() Method Rather Than .click(), .bind(), .hover(), .load(), .ready(), Etc"