Sergio
Sergio

Reputation: 1239

Jquery function problem

I have a problem with this Jquery function. The the simplifide code looks like:

$(document).ready(function(){

    $(".brs").toggle(function() {
        var commid=$(this).attr('kid');
        $('.comment'+commid).html('the new text - <a href="javascript: void(0)"  class="brs2" kid="'+ commid +'">click to change the text</a>');
    }, function () {
        var commid=$(this).attr('kid');
        $('.comment'+commid).html('new text');
    });

    $(".brs2").click(function() {
        alert("test"); 
    });

});

HTML code:

<div class="comment1">some text</div> | <a href="javascript: void(0)"  class="brs" kid="1">test link</a>

When the text changes in the div "comment1" the link that runs another function (class "brs2") does not work. What could be the problem?

Thanks for all sugestions.

EDIT:

If the Jquery code looks like:

$(document).ready(function(){
$(".brs").toggle(function() {
var commid=$(this).attr('kid');
$('.comment'+commid).html('the new text - <a href="javascript: void(0)"  class="brs" kid="'+ commid +'">click to change the text</a>');
}, function () {
var commid=$(this).attr('kid');
$('.comment'+commid).html('new text');
});

$(".brs2").click(function() {
alert("test"); 
});

});

And the HTML:

<div class="comment1">some text</div> | <a href="javascript: void(0)"  class="brs" kid="1">test link</a>

I can't use live() to trigger the same toggle function with new link that appears in comment1 div?

Upvotes: 1

Views: 67

Answers (3)

Rafay
Rafay

Reputation: 31043

use live instead of click because you are dynamically inserting the link in the DOM

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

here is the fiddle http://jsfiddle.net/7E8aG/1/

here is a link to jquery live http://api.jquery.com/live/

Edit

if i have understood well may be you can do it like

$(".brs2").live('click',function() {
    if($(this).is(':visible'))
    {
        $(this).fadeOut("slow");
        $("div.comment1").html("new text");
    }    
});

http://jsfiddle.net/7E8aG/2/

Upvotes: 1

tomsseisums
tomsseisums

Reputation: 13377

Because the link (.brs2) isn't in DOM when the page is loaded. You have to live(); bind the click event.

$('.brs2').live('click', function(){
    alert('test');
});

You could as well use delegate();, but that's an overkill for such a simple task and a bit more complicated.

Update

If I understood the question correctly, you can bind multiple events on live or you can delegate them. Please see the post here - Using jQuery .live with toggle event - it should give you the information you're looking for. I can provide the answer only tomorrow, it's late here.

Upvotes: 3

rabudde
rabudde

Reputation: 7722

Or do:

$('.comment'+commid+' .brs2').click(function() {
        alert("test"); 
});

after html manipulation in first toggle function

Upvotes: 0

Related Questions