Neeraj Mehta
Neeraj Mehta

Reputation: 1705

Click Function sometime firing twice,thrice and much more

I have use this click function for some event to call but when i am clicking the class it is sometime firing twice,thrice and much more .

Please give me proper suggestion for this code and how to correct it.

 $(".PositiveReaction").unbind("click").click(function () {
        var itemGraphId = this.id;
        itemGraphId = itemGraphId.replace("Like", "");
        $.ajax({
            type: "Post",
            url: "/React/AddReact",
            dataType: "JSON",
            data: { "itemGraphId": itemGraphId, "reactionTypeEnum": "POSITIVE" },
            success: function (data) {
                $.each(data, function (i, item) {
                    $("#CountLike" + item.GraphID).html(item.CountPositiveReactions);
                    $("#CountDisLike" + item.GraphID).html(item.CountNegativeReactions);
                });
            },
            error: function (req, status, error) {}
        });
  });

Upvotes: 1

Views: 450

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

Use a delegated event attached to a non-changing ancestor. Then you do not need to turn it on and off (depending on your app logic of course):

 $(document).on("click", ".PositiveReaction", function () {

It will work for current and future matching elements.

A delegated event works by listening for events bubbling up to a non-changing ancestor. document is the default if there is nothing convenient/closer. It then applies the jQuery selector to the elements in the bubble chain. It then calls the function for any matching element that caused the event. This means the element does not have to match until event time, rather than when the event handler is created.

Note: Do not use 'body' for delegated events, as styling can cause the body to have 0 height and events may not occur! Always use document as the fallback.

Should you actually need to turn a delegated handler off, use a namespace on the event name:

Turn on with:

 $(document).on("click.myapp", ".PositiveReaction", function () {

Turn off with:

 $(document).off("click.myapp");

Upvotes: 1

Ekansh Rastogi
Ekansh Rastogi

Reputation: 2526

Best way is to rewrite the method in the following way

$(document).on("click",".PositiveReaction", function(){ ajaxFunction();})
$(document).off("click",".PositiveReaction",function(){ ajaxFunction();})

function ajaxFunction(){
 //Do stuff here
}

Upvotes: 0

Related Questions