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:
- navigate to index2.html
Run #1:
- click button "Make things happen"
- hover over "Click this to toggle Stuff"
-- cursor changes to a hand - click "Click this to toggle Stuff"
- "Stuff" toggles correctly.
Run #2:
Steps 1, 2, 3 as before.
- "Stuff" does not toggle.
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?

loadData, you are attaching a function to the click and hover events. Attaching a function several times to an event will trigger it the same number of times you attach it..hover()and.click()apply eventhandler to you button so you should define these eventhandlers only once to the element not multiple times. You could apply the eventhandlers when page has finished loading for example. Have a look at api.jquery.com/ready