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 and watch the console output. The click function gets called multiple times when it should only be called once.
The commented out code at the end works just fine. Am I doing something wrong? I’m new to jQuery.
Here’s the code:
function toggleDiv(status)
{
console.log("toggleDiv(" + status + ")");
if (status) {
$("#test").html("Goodbye");
}
else {
$("#test").html("Hello");
}
$("#test").click(function() {
toggleDiv(!status);
});
// Non-jquery method works fine....
//document.getElementById("test").onclick = function () {
// toggleDiv(!status);
//}
}
Update: looks like there are lots of ways to skin this cat. The real issue here was my not understanding that the jQuery “click” functions ADDS another handler. I thought it REPLACED the current handler.
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 useonclick / onmouseover / onmouseout / etcevents 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