I've found similarly titled questions on SO, but none seem related to my issue.
This one has been driving me nuts all day and most of the night.
First, the what the running code looks like:

Next, an MCV version of my code:
<!DOCTYPE html>
<!-- file: index2.html -->
<html>
<head>
<link rel="stylesheet" href="css/style2.css">
</head>
<body>
<form id="form-container">
<button id="submit-btn">Make things happen</button>
</form>
<div id="toggler">Click this to toggle Stuff</div>
<div id="stuff-container">
Stuff
</div>
<script src="js/libs/jquery.min.js"></script>
<script src="js/script2.js"></script>
</body>
</html>
// file: script2.js
function loadData() {
$('#toggler').hover(
function() {
$(this).css('cursor', 'pointer');
},
function() {
$(this).css('cursor', 'text');
});
$('#toggler').click(function() {
$('#stuff-container').toggle();
});
return false;
};
$('#form-container').submit(loadData);
/* file: style2.css */
#stuff-container {
display: block;
}
And the behavior:
Run #1:
Run #2:
Steps 1, 2, 3 as before.
Using console.log() calls, I found that each function in script2.js executes multiple times if the "Make things happen" button has been clicked more than once.
e.g., if the button has been clicked 5 times since page reload, when I do Step 2 above, the first .css() in hover() is executed 5 times.
So, if the button has been clicked any even number of times, the toggle() calls have no effect.
The questions:
What (probably very basic) concept am I missing? How do I prevent the multiple executions of each function?
That is because the $('#toggler').hover and $('#toggler').click() binds new (additional) event handlers each time it is executed. And you execute those each time you press on the button which in turn runs the loadData function.
So,
In general it will work on the odd runs and fail on the even ones.
You should only bind once.
On solution is to unbind before re-binding
$('#toggler').off('mouseenter mouseleave').hover(...);
$('#toggler').off('click').click(...);
But it really depends on what other things you want to do inside the loadData function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With