I have some javascript that should print a string to the console, however it also executes another function that is defined elsewhere. The script is:
var run_once = function() {
console.log("run_once has executed.");
};
var to_print = "This should print.";
run_once();
document.getElementById("test_button").addEventListener("click", console.log(to_print));
HTML:
<!DOCTYPE html>
<html>
<body>
<form method="post">
<button id="test_button">test</button>
</form>
<script src="../scripts/drill_creator.js"></script>
</body>
</html>
When the page is refreshed I get the following printed to the console:
run_once has executed. drill_creator.js:2
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
Then upon clicking the test_button, the console displays:
run_once has executed. drill_creator.js:2
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
run_once has executed. drill_creator.js:2
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
Why does run_once get called when a click occurs? Also, why does "This should print." get printed when the page loads but the button isn't clicked?
Thanks very much
Michael
EDIT: I have changed the last javascript line to:
document.getElementById("test_button").addEventListener("click", function(){console.log(to_print)});
Which solves the problem of the event firing on page load (thanks very much Joshua K) however this still results in run_once being called when the button is clicked. After loading the first two lines below are displayed, then clicking the button, displays the next three:
run_once has executed. drill_creator.js:2
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
run_once has executed. drill_creator.js:2
SECOND EDIT:
As Joshu K mentions in the comments on his answer, the button element acts as a submit by default. To get a button that does not trigger the form's action, but can be used to call additional javascript, one can use:
<input type="button" value="text on the button">
After making the two changes above, the code functions as I'd hoped.
Thank you all for your suggestions.