Unobtrusive javascript and jquery selectors
Jquery is a great library used by many. Those who are just starting out can become a bit confused by the jquery selector format. I want to take some time today and give you a primer and some examples on using selectors in jquery. Using them effeciently can save you time and headache.
If you aren't familiar with unobtrusive javascript techniques, now would be a good time to brush up. If you create your javascript in an "unobtrusive" way, this means that you keep your javascript code separated from your presentation ( not intermingled with the html ). Jquery selectors give you lots of ways to code your javascript this way. One factor that makes unobtrusive javascript techniques useful is that your javascript code can be more centralized. If you change a method call you won't need to update it in the html, you would update the event binding for the objects that need to call the new method.
Obtrusive javascript example:
<input type="button" onclick="call_a_function()" value="Go" />
In this example, the function call is embedded within the html. This unnecessarily bloats the html and can cause you headache later.
Unobtrusive javascript example:
<input type="button" class="search_btn" value="Go" />
and in your javascript file after jquery inclusion:
$(function(){ $('.search_btn').click(function(){ call_a_function() }); });
The immediate benefits may not be apparent. Lets say however that you have many buttons spread throughout different pages that you need to call a function with. If you embed the call within your html and then change the function signature you would then need to update all the locations in the html where the call is made. If you used unobtrusive javascript and had the classes assigned to all your buttons, then you would just need to update the call in a single place which would then take effect for all buttons.
As you build more complex implementations/applications you will find even more benefits to coding your javascript in an unobtrusive way.