Time for more jQuery goodness
No, it’s not what you think. I’m not posting some grand tutorial on how to re-animate the dead with jQuery… at least not yet. What I am going to do is post a few things that I either stumbled into, or had to figure out for myself while using jQuery.
1st – Sometimes you may find yourself writing huge functions, or the like, in which you continually use the selector ” $(this) “. There’s nothing wrong with that, I use it all the time. However something you really should keep in mind is that every time you call that selector, you are throwing more drag on the cpu/browser/rendering of your site. How do you alleviate this problem? simple, just set the $(this) selector into a variable.
/* how not to code */ $(document).ready(function(){ $(this).doSomething(); $(this).click(function(){ $(this).runMore(); }); $(this).yepEvenMore(); }); /* how you should code */ $(document).ready(function(){ var $this = $(this); $this.doSomething(); $this.click(function(){ $this.runMore(); }); $this.yepEvenMore(); }); |
2nd – This really should be a no-brainer, but after spending over 15 minutes trying to get the selector to work (and browsing several jQuery sites, checking my cheat sheets, etc.) I finally found the answer to using a selector within a selector. I believe the answer came from the jQuery google-group. It was as simple as the following example.
$("#left label[for=" + $this.attr("id") + "]").addClass('active'); |
You can see that I had a div with an id of ‘left’ and I wanted a particular label inside that div to have a class of ‘active’ applied to it. This worked with a click event (not shown).
3rd – What happens when you have some images that when clicked you want to change the value of a form? Say for example that you have some logo’s of credit cards that when clicked on you want to change a select box in your form to show the value of that credit card? The solution for this one I couldn’t find anywhere on the interweb, so I spent plenty of time figuring this one out. It works, and I’m fairly happy with it. NOTE: you must be using jQuery 1.3+ to make this work, the changes made in this version of jQuery allow you to do this type of selector.
$("#payment-type-ful img").click(function(){ var card = $(this).attr('alt'); $("#policyId").val(card); }); |
Yep, there’s a div with an id of ‘payment-type-ful’ and I need any images under it, and when clicked on I set up a variable called ‘card’ that is set to the alternate text of the clicked-on image. I then select the input select and set the current value to ‘card’. Simple? oh yeah, easy, absolutely.
That sums up a few quick little jQuery gems that I’ve been using recently. As per usual, if you have any questions, comments, or tips of your own, feel free to throw them in the comments, thanks!