Brooke Holmes
Brooke Holmes

Reputation: 1622

jQuery click listener fires when it's not supposed to

With the following block of code, when I press #transfer-button the first time round, it alerts with the correct dialog, but when performed a second time before refreshing the page, it continues sequencing with the first dialog clicked until the last dialog clicked. For example, I press "WIlliam" and it will come up with a dialog saying "William", and then I press "Lucy" and a dialog saying "William" will pop up, and then once closed "Lucy" will immediately pop up as well. How do I fix this?

$("#person1").click(function () {
$("#transfer-info").html("Transfer to Lucy.");
$("#transfer-button").click(function () {
    alert("Lucy");
})
})
$("#person2").click(function () {
$("#transfer-info").html("Transfer to William.");
$("#transfer-button").click(function () {
    alert("William");
})
})

Upvotes: 0

Views: 44

Answers (2)

Achrome
Achrome

Reputation: 7821

When switching, you are simply adding another event listener, so you end up with multiple event listeners, with both of them firing.

You can do something like this.

$("#person1").click(function () {
    $("#transfer-button").unbind('click');
    $("#transfer-info").html("Transfer to Lucy.");
    $("#transfer-button").click(function () {
        alert("Lucy");
    });
});

$("#person2").click(function () {
    $("#transfer-button").unbind('click');
    $("#transfer-info").html("Transfer to William.");
    $("#transfer-button").click(function () {
        alert("William");
    });
});

Upvotes: 1

Yann86
Yann86

Reputation: 1017

try

$("#person1").click(function () {
$("#transfer-info").html("Transfer to Lucy.");
$("#transfer-button").off('click')
$("#transfer-button").click(function () {
    alert("Lucy");
})
})
$("#person2").click(function () {
$("#transfer-info").html("Transfer to William.");
$("#transfer-button").off('click')
$("#transfer-button").click(function () {
    alert("William");
})
})

Upvotes: 0

Related Questions