jQuery’s Clone() and FireQuery

So there was this need for providing ajax-style add/remove item-rows on the last project I worked on.  What I thought might be pretty straight-forward to achieve using jQuery-fu eventually turned out to be little hairy for me.

The approach that I used to implement this was to use a hidden item(a div with some content in this case) and clone it using the jQuery clone() method to make a new copy of the item and then append it to the collection under a parent div.  The cloning and adding worked like a charm. What bothered me was the remove of the item-row. Each item-row had a remove link/button to delete the item. The remove was supposed to work using the jQuery click event handler on the remove link/button. It did’nt work as expected :-(.  The click event handler was’nt getting hit for some reason and I did not have clue as to why as the same remove handler was working without issues in a different section on the same page.

What I came to my rescue was FireQuery.

FireQuery is a cool little add-on for Firefox that integrates with Firebug. It allows inspection of jQuery expressions, methods, events in the firebug console making it a great debugging assistant for jQuery. Using FireQuery, I was able to confirm that the cloned item-rows did not have the click remove handler attached to them. This made me realise that the clone() was not copying the jQuery event handler after all.  Thanks to Google, I finally figured out clone(true) would fix the problem and it did! Apparently, clone(true) is like a deep copy of the DOM element/object along with its events.

I m a jQuery newbie but I have already started loving it over Prototype and other JS libraries I have used in the past. Hoping to make more use of it (and FireQuery too!) in the future.

JQuery Clone and Append


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s