Rip's Domain

Chaining a bind and trigger with jQuery to elminiate functions

Posted in Jquery by rip747 on July 17, 2008

yesterday david shuck posted some jquery code he was using to toggle the display of some form information. one of the things i noticed about his code was that he was using jquery to bind to the change event of a radio button, but the code to acutally toggle the display was contained in a separate function.

i commented him back about how he could combine these two functions into one jquery chain thus making the code a little more readable. today i want to share this with you, let’s take a look at the two functions:


function toggleCreditCardCompanyPanel()	{
    if ($("#RequireCCInfo").attr("checked") == true)
    else $("#CreditCardCompanyPanel").hide();


basically the first function bind to the change event of a checkbox with an id of RequireCCInfo and then calls the toggleCreditCardCompanyPanel to toggle the display of the panel.

so how could chaining in jquery help us clean this up a little? remember that with jquery you can bind a function to an event and also trigger event. with this knowledge you can do things like:

$(“#RequireCCInfo”).bind(“change”, function(){
// your code

as you can see from the code above, we’re binding some code to the change event and then immediately after triggering it, this is the same thing a creating a separate function and then calling it. armed with this knowledge we can now perform the clean up:

$(“#RequireCCInfo”).bind(“change”, function(){
$(“#RequireCCInfo:checked”) ? $(“#CreditCardCompanyPanel”).show() : (“#CreditCardCompanyPanel”).hide();


One Response

Subscribe to comments with RSS.

  1. Dinh Dinh said, on June 24, 2011 at 8:33 pm

    Thank you so much !!!
    Very nice and precise example – just what I need

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: