1110
1110

Reputation: 6829

Multiple elements with same class make jquery click event to fire multiple times

I display user comments. Each comment is one div and each div has <a> tag with class 'commentLikeLink'. I bind jquery click event to 'commentLikeLink' class but If I have 10 comments and click on one like button I get event fired 10 times.
I know that this happen's because I have same class multiple times. But How to stop this?
Here's the code:

...
<div class="commentBox"">
...
@Html.ActionLink(likeText, "LikeComment", "Comment", null, new { id = Model.CommentId, @class = "commentLikeLink" })    
...

Event code:

$(function () {
            $('.commentLikeLink').click(function (event) {
                var commentId = event.target.id;

                $.ajax({
                    url: this.href,
                    type: 'POST',                    
                    data: { commentId: commentId },
                    context: this,
                    success: function (result) {
                        if (result.msg == '1') {
                            $(this).text('Dislike');
                        }
                        else if(result.msg == '2') {
                            $(this).text('Like');
                        }

                    }
                });
                return false;
            });
        });

Upvotes: 5

Views: 15170

Answers (3)

Mouhamed Halloul
Mouhamed Halloul

Reputation: 209

yes binding the click event to the class is a better solution, but it can actually get fired multiple times if you use it on the item it self or the class it self !

so instead of having this : $('.commentLikeLink').click(function (event) {//do things here }

you should do this and it will only fire once :

$(document).on("click", ".commentLikeLink", function (ev) {
    //do things here
});

Upvotes: 4

kprobst
kprobst

Reputation: 16651

You shouldn't be getting 10 clicks. You can bind the click event to the class, but the context in which the event is fired is the individual element, so if you had some markup that looked like this:

<p>
    <a href="#" class="clickItem">Liked?</a>
    <br />
    <a href="#" class="clickItem">Liked?</a>
    <br />
    <a href="#" class="clickItem">Liked?</a>
    <br />
    <a href="#" class="clickItem">Liked?</a>
</p>

Then this would work, setting the link text to "Liked!" as each one is clicked:

$(document).on("click", ".clickItem", function (ev) {
    $(this).text("Liked!");
});

Have you debugged the code? Are you sure you're getting 10 clicks all at once?

Upvotes: 6

Joel Grannas
Joel Grannas

Reputation: 2016

I had this happen before when i accidently included the same .click script function multiple times in the page. Make sure your javascript is only included once

Upvotes: 3

Related Questions