Ben
Ben

Reputation: 123

jQuery firing twice, event bubbling?

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.

Upvotes: 9

Views: 24602

Answers (5)

George SEDRA
George SEDRA

Reputation: 786

$('.scroll-content-item').unbind('click').bind('click', function(e) {
    alert("clicked");
});

Upvotes: 3

illvm
illvm

Reputation: 1346

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');

Upvotes: 3

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

$('.scroll-content-item').click(function (event) {

Upvotes: 9

jyoseph
jyoseph

Reputation: 5455

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?

Upvotes: 7

Nick Craver
Nick Craver

Reputation: 630469

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");
  //...
});

Upvotes: 6

Related Questions