Blog Coding

Remove jQuery plugins at runtime

A good friend of mine asked me last week how she could remove jCarouselLite on the fly, after it had been instantiated. Allow me to share with you guys how to do this, and hopefully show you a trick or two along the way.

As you may know, a typical jCarouselLite plugin is instantiated as such:
$(function() { $(".anyClass").jCarouselLite({ btnNext: ".next", btnPrev: ".prev"}); });

where “.anyClass” is the name of your gallery container, “.prev” and “.next” are the gallery’s previous and next navigation links, respectively.

Removing the plugin at runtime is fairly simple once you understand what is involved:
$('.anyClass').jCarouselLite = null;

These 3 lines allow you to re-initialize jCarouselLite later on within the same page. Pretty simple and neat, isn’t it?
Let’s decompose what just happened so you may get a better understanding.
$('.anyClass').jCarouselLite = null; removes the jCarouselLite instance from our gallery. In other words, you will have to reinitialize jCarouselLite if you want to reuse it on this page for this gallery.
This isn’t all, however. When jCarouselLite is initialized, it creates what we call event bindings.
Whenever you destroy the jCarouselLite instance the bindings are still lingering and problems will start occurring if you re-initialize jCarouselLite on the same page, for the same gallery, as the click events on the navigation links will have been bound twice.
To prevent this issue from occurring, we add the two following lines:

Which brings me to one last pro-tip about dealing with groups and bindings.
There are two main ways to deal with group bindings in jQuery:
– The first one is fairly common. It consists of using a common class to all elements of a similar group.
$('.clickable').bind('click', function(){ alert("Hi, I'm clickable!"); });

In the code above, all elements of the class “clickable” will have the mouse click event bound (then unbound) to them.

There is however a second, more mystical way to do this in jQuery: Namespacing.
Let’s say you create an instant link preview feature that you want to disable and re-enable at will on your page. We will call our namespace “linkPreview”.
Here’s the event binding to our namespace:
$('a').bind('mouseover.linkPreview', myPreviewFunction);

And the event unbinding, just as easily:

This makes it easy to unbind only specific events from our elements. In this case, all other mouseover events would still be bound to our page links. Isn’t this amazing?