2

I have an ajax request which brings in new posts and each post has a toggle button to show and hide an element which is hidden by default.

The below code works, but with the inserted ajax data it only works the first time (open) and not the second (close)

$(".voice_btn").live( 'click', function(){
    $(this).toggleClass('active voice_btn');
    $(this).closest('.element').children('.voice_box').toggle(300);
    $('.tipsy').hide();
    $(this).attr("title", ($(this).hasClass("active")?"Close":"Open") + " voicebox");
    return false;
});
animuson
  • 50,765
  • 27
  • 132
  • 142
Darcbar
  • 888
  • 1
  • 8
  • 25

2 Answers2

3

If you remove the voice_btn class from the element, it will no longer trigger the click event because it no longer satisfies the selector.

change

$(this).toggleClass('active voice_btn');

to

$(this).toggleClass('active');
Kevin B
  • 92,700
  • 15
  • 158
  • 170
2

just update line 2 to only toggle the active class, because after the first time your code runs the voice_btn class is removed, and your live function is no longer attached to your element:

$(".voice_btn").live( 'click', function(){
    $(this).toggleClass('active'); // <- notice the change in this line
    $(this).closest('.element').children('.voice_box').toggle(300);
    $('.tipsy').hide();
    $(this).attr("title", ($(this).hasClass("active")?"Close":"Open") + " voicebox");
    return false;
});
Bassam Mehanni
  • 14,186
  • 2
  • 30
  • 41
  • Thats funny, this worked with a .click but not with a .live, why is this? Thanks it works great now! – Darcbar Jan 31 '12 at 17:17
  • I think it's because click is attached to the element and the selector becomes irrelevant after that, while live is always monitoring the DOM for changes – Bassam Mehanni Jan 31 '12 at 17:24
  • @BassamMehanni `.live` does not monitor the dom for changes, it simply binds the click event to the `context`, which by default is the `document`. Then, every time a click event reaches the document, it is tested against the selector. If it matches the selector, the event handler is triggered. Event Delegation. – Kevin B Mar 05 '12 at 22:30