I am getting unexpected results with jQuery trying to set the \"click\" method of a div. Please see this jsfiddle. Be sure to open the console window. Click the word a few times
The jQuery click function doesn't overwrite a previous click handler but instead adds the new one to a queue. So when click is called again, a new click handler is added along with all the old ones.
To prevent this, you just need to clear the old handlers before defining your new one.
function toggleDiv(status)
{
console.log("toggleDiv(" + status + ")");
if (status) {
$("#test").html("Goodbye");
}
else {
$("#test").html("Hello");
}
$("#test").unbind();
$("#test").click(function() {
toggleDiv(!status);
});
}
You may also want to look at the .toggle() event handler.
UPDATE: To be clearer about .toggle()
, this will also do what you want:
$("#test").toggle(
function(event) { $(event.target).html("Goodbye"); },
function(event) { $(event.target).html("Hello"); }
);