Person
Person

Reputation: 523

Can't make jQuery callbacks to work properly while calling same function repeatedly

I have a simple share button aside every post, I'm using .toggle() function to show and hide the options. The code looks something like this:

<div id="posts">
<div class="post">
<div class="content">
Post content
</div>
<div class="share">
  <div class="trigger"> Share </div>
  <div class="hidden"> Share on Facebook </div>
  <div class="hidden"> Share on Twitter </div>
</div>
</div><!-- each post -->
<div id="new">
</div><!-- new post container -->
</div><!-- Posts -->

<script>    
    function shareThis(){
        $('.trigger').click(function(){
            $(this).siblings().toggle();
        });
    }    
    $(document).ready(function(){
        shareThis();
        $('#new').load("/post2", function(){
            shareThis();
        });
    });
</script>

I call this function once when the page loads, and then every time a new post is loaded.

The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded. I also tried this with 'each' function but same result.

So it's just working for the last call, similar to these question i found here and here, and some others, but didn't get a solution for my problem there.

Thanks!

Upvotes: 1

Views: 130

Answers (2)

TomFuertes
TomFuertes

Reputation: 7270

Try binding the click to the document instead. Only need to do it once :)

$(document).on('click', '.trigger', function () {
    $(this).siblings().toggle();
}).ready(function () {
    $('#new').load("/post2");
});

http://api.jquery.com/on/

http://training.bocoup.com/screencasts/more-efficient-event-handlers/

Upvotes: 1

PSL
PSL

Reputation: 123739

The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded.

Your issue could be that you are binding the event twice (or as many number of times you load #new contents) to the existing .trigger by calling shareThis inside the load callback. So basically when you click on the old .trigger it will trigger the handler twice, i.e toggling it twice which keeps them in the same state. SO either bind the event to the newly added ones alone or turn the click event off and turn it on in the function shareThis:

 function shareThis(){
        $('.trigger').off('click').on('click', function(){
            $(this).siblings().toggle();
        });
    }  

You could also try:

function shareThis(ctx){
    ctx = ctx || document;
    $('.trigger', ctx).click(function(){
        $(this).siblings().toggle();
    });
}    
$(document).ready(function(){
    shareThis();
    $('#new').load("/post2", function(){
        shareThis(this);
    });
});

Upvotes: 1

Related Questions