I have been using jQuery for just over a year now after being introduced to HTML5 and JavaScript around about the same time.
What I would like to know is, the best way to add a click event to an element? There are SO many ways to do this. Primarily, most ways come from jQuery, but you also have the onclick attribute for HTML. But, I have been advised not to use the onclick event because it's best practice to keep the HTML purely for markup and structure.
Which leaves me with just jQuery. But then again, there's so many ways to do this. I have:
- $.bind(...)
- $.click(...)
- $.on(...)
To name a few, but then if I am creating some content dynamically, I could do,
- $('<a>', {
- 'click': function(e) { /*...*/)
- })
Or I could do:
- $('<a>').on('click', function(e) { /*...*/})
My thoughts are to ALWAYS use the .on(...) method because of its diversability, it also means we are ALWAYS using just one method to assign all event handlers.
My other question is, why is there so many ways to use .on(...)? (Taken from
here) I could use on in the following instances:
- // Bind
- $( "#members li a" ).on( "click", function( e ) {} );
- $( "#members li a" ).bind( "click", function( e ) {} );
-
- // Live
- $( document ).on( "click", "#members li a", function( e ) {} );
- $( "#members li a" ).live( "click", function( e ) {} );
-
- // Delegate
- $( "#members" ).on( "click", "li a", function( e ) {} );
- $( "#members" ).delegate( "li a", "click", function( e ) {} );
If you could clarify those points - it would be greatly appreciated!
Thanks