views:

39

answers:

2

hi there,

I hope you can help me with a problem; first, please don't worry about my language skills, I come from germany and I don't speak english every day, unfortunately :-(

I'm using jquery tabs in ajax mode and have some problems concerning click events. An example: I initalizate in my first and second tab such a click function on a button:

$(".new_message").live("click", function() { alert("test"); });

Now imagine following: a user clicks on the first tab and the button marked with class "new_message" is holding the defined click function. Up to here everything is fine, but on selecting the second tab, which has got the same button, there is a problem: javascript alerts two time "test", but I only want to get it once. I searched a lot to solve this problem, all solutions I got were to use the live function, but i did so and it's not working.

Is there a possibility to make this work, even in ajax tabs? Please note, that the javascript content of a tab was not loaded until it was selected. I'm not caching my tabs, so the content of the tab fires again and again (so if you click on tab 1, than tab 2 and again tab 1, the script alerts three times "test")...

I hope you get it, whatever ;o) Cheers, Bamboo

+1  A: 

You could simply check if the event is already bound, since it is a live binding:

var bound = false; // this should exist on the containing page and not in each tab

Then wire it up like so:

$(function(){
    if (!bound)
    {
        $(".new_message").live("click", function() { alert("test"); });
        bound = true;
    }
});

I ran into a problem when using a wizard type ajax interface where the live() jQuery events would become bound, bound, and then rebound, as you navigated back and forth through the wizard. To ensure that any live events would be properly set you need to call the die() method first and then rebind.

$("#myClickableThing").die("click").live("click", function () {
    // do work
});

And to add it as a new jQuery function you can try this:

jQuery.fn.resurrect = function (eventType, callback) {
    $(this).die(eventType).live(eventType, callback);
};

Now you can call resurrect like this:

$("#myClickableThing").resurrect("click", function() { 
    // do work
});

I wrote a blog post about exactly this issue and created a little helper function to handle it.

hunter
thank you! that was exactly that i was looking for!
Tobias Bambullis
want to set my response as the answer?
hunter
A: 

Use event delegation on an element that contains the tabs.

Example:

$('#tabs-container')
  .bind(
    'click',
    function(e){
      if($(e.target).is('.new_message')){
        alert('test');
      }
    }
  );
Thomas