Saturday, September 4, 2010

jQuery die() function Example/Demo

I had previously posted about the live() function which is used for binding events. jQuery provides another function die(), which does the opposite of live function. Which means it removes all the event handler that were attached by live function. Let's see how we can use die function.

Place two buttons "Live" and "Die". "Live" button when clicked, binds the click event to "a" tag where die button when clicked removes the click event.
<a href="#">Click Me </a>
<input type="button" value="Live" id="btnLive" />
<input type="button" value="Die" id="btnDie" />
jQuery code for live and die function
   $("#btnLive").click(function () {
     $("a").live("click", function() {
          alert('I am clicked');

   $("#btnDie").click(function () {
That's it. When btnDie button will be clicked, click event from all the a tag will be removed.

See live Demo and Code.

If you want to remove all the function attached to a tag like click, mouseover, mouseout etc. then you can easily remove it with die function
Above code will remove all the attached event with a tag. Cool, right? :)

Feel free to contact me for any help related to jQuery. I will gladly help you.