Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery firing twice, event bubbling?

Tags:

jquery

I have looked at all of the issues people are having with event bubbling and jQuery firing twice, but I can't figure out this issue. I am only clicking in one DIV at a time, but the click handler is firing twice.

HTML

<div class="scroll-content-item" data-pid="1773">
    <img src="somefile" class="mixdock-img" data-pid="1773"/>
</div> 
<div class="scroll-content-item" data-pid="1777">
    <img src="someotherfile" class="mixdock-img" data-pid="1777"/>
</div> 

jQuery...

jQuery(document).ready(function($) {

var count = 0;

// On click, hide the currently displayed post and show the one clicked
$('.scroll-content-item').click(function () {
    count += 1;
    alert("count = "+count);
    event.stopPropagation();
});

});

What this does is show two alerts per click, each with the same count. Count does increment on each click.

like image 278
Ben Avatar asked Nov 29 '10 19:11

Ben


5 Answers

I was not able to reproduce the issue on jsbin: http://jsbin.com/ixabo4

Is it possible that you have included the jQuery script twice?

like image 113
jyoseph Avatar answered Nov 12 '22 07:11

jyoseph


It sounds like overall your code is executing twice, two entire instances of your:

jQuery(document).ready(function($) {
  //...
});

...are executing (each with their own count variable), ensure the script isn't being included twice in the page. To confirm this is the issue, you can add an alert (which you should see twice at the moment):

jQuery(document).ready(function($) {
  alert("init");
  //...
});
like image 20
Nick Craver Avatar answered Nov 12 '22 08:11

Nick Craver


You have to pass the event variable into your function like so:

$('.scroll-content-item').click(function (event) {
like image 30
Richard Marskell - Drackir Avatar answered Nov 12 '22 08:11

Richard Marskell - Drackir


jQuery(document).ready(function($) {

        var count = 0;

        // On click, hide the currently displayed post and show the one clicked
        $('.scroll-content-item').click(function(e, ui) {
            e.stopPropagation();
            count += 1;
            alert("count = " + count);
        });

    });

Works fine in my tests. Even with nested divs with the class "scroll-content-item". I would make sure you aren't attaching a listener to the click handler more than once.

If you can't find a place where the code is being called twice add the following before you attach the listener:

$('.scroll-content-item').unbind('click');
like image 3
illvm Avatar answered Nov 12 '22 07:11

illvm


$('.scroll-content-item').unbind('click').bind('click', function(e) {
    alert("clicked");
});
like image 3
George SEDRA Avatar answered Nov 12 '22 07:11

George SEDRA