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 same problem was happening with me . Joseph Erickson's answer about unbind() works. If it helps , here is the summary of how onclick event ended up being called multiple times in my code :
I solved this as per suggestion given by Joseph Erickson. Within the AJAX callback, I do this now : $(".msgLinkDiv").unbind(); (".msgLinkDiv").click(function(e){do my stuff});
Most likely you are running toggleDiv
mutliple times, resulting in the click event being bound multiple times. Bind the click event outside of the toggleDiv
function.
var status = false;
function toggleDiv()
{
console.log("toggleDiv(" + status + ")");
if (status) {
$("#test").html("Goodbye");
}
else {
$("#test").html("Hello");
}
status = !status;
}
$("#test").click(function() {
toggleDiv(status);
});
After your if, you're adding another click event to #test
. It will call all click handlers when it's clicked. You probably don't need that at all since onclick
is defined in the html.
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"); }
);
You are setting a new .click()
eventHandler each time you keep clicking it (which in turn creates even more events). On a side note, try to never use onclick / onmouseover / onmouseout / etc
events on DOM elements. In Internet explorer these create script blocks (that you can visibly see if you use Visual Studio. Pages with thousands of these slow down performance tremendously!
It looks like you are trying to achieve this:
jsFiddle DEMO
$("#test").on('click', function() {
var this$ = $(this),
_status = !!this$.data('status'); // force to boolean
// ^will default to false since we have no data-status attribute yet
this$.html(_status ? 'Hello' : 'Goodbye')
.data('status', !_status);
});
The cleanest solution would be this: http://jsfiddle.net/kannix/fkMf9/4/
$("#test").click(function() {
$(this).text(($(this).text() == "Hello") ? "Goodbye" : "Hello");
});