Reputation: 5135
I have some "complicated" clicking events that I can't figure it out how to fix it.
I have a click event on some elements added later on the page, so I used .on
.
What I am trying to achieve is that when you click the .neuron, you shouldn't be able to click another .neuron, or neither the one you clicked before. This is why I added the .off
function.
The problem is that, after 2-3 times of opening/closing the neuron, the clicking event will trigger 2 times, then 4 times, then 8 times, and so on. I don't understand why.
Here is the part of jQuery is relevant:
$("#nn_container").on("click", ".neuron", zoom_neuron);
function zoom_neuron() {
$("#nn_container").off("click", ".neuron", zoom_neuron);
console.log("off");
/* do some stuff */
$("#close_neuron").click(function() {
/* do some stuff */
$("#nn_container").on("click", ".neuron", zoom_neuron);
console.log("on");
});
}
What is wrong with it? Why it continues to increase in event calling?
Upvotes: 0
Views: 103
Reputation: 1183
$("#nn_container").on("click", ".neuron", zoom_neuron);
function zoom_neuron() {
$("#nn_container").off("click", ".neuron", zoom_neuron);
console.log("off");
/* do some stuff */
$("#close_neuron").off('click').on('click', (function() {
/* do some stuff */
$("#nn_container").on("click", ".neuron", zoom_neuron);
console.log("on");
});
}
That will make sure that #close_neuron
has only one bound click event at a time. This assumes there are no other places in the code that bind a click event to #close_neuron
.
Upvotes: 1