I am new to javascript and having a problem with some code.
It seems to me some of my functions are running even when not called.
The page loads and DOMContentLoaded event fires which is expected.
DOMContentLoaded event calls getRandomNumber which is also expected.
I enter a guess of the number and click submit, the mouseup event happens,
so far so good. But then getRandomNumber is called from the DOMContentLoaded
event which is not expected. I do not understand why DOMContentLoaded call back
is run again. I thought it runs once when all html, css and scripts are loaded.
There was code in those function but I replaced with alerts to
narrow down what is happening.
Thanks in advance!
It seems to me some of my functions are running even when not called.
The page loads and DOMContentLoaded event fires which is expected.
DOMContentLoaded event calls getRandomNumber which is also expected.
I enter a guess of the number and click submit, the mouseup event happens,
so far so good. But then getRandomNumber is called from the DOMContentLoaded
event which is not expected. I do not understand why DOMContentLoaded call back
is run again. I thought it runs once when all html, css and scripts are loaded.
There was code in those function but I replaced with alerts to
narrow down what is happening.
Thanks in advance!
Code:
<script>
var subBtn = document.getElementById('submit'); //submit button
subBtn.addEventListener('mouseup',mup ); //release click on submit button
function mup(){
alert("mouseup");
}
function getRandomNumber() { //normally genertates random number
alert("Got random#");
}
document.addEventListener("DOMContentLoaded", (event) => //runs after page fully loaded
getRandomNumber();
alert("DomContentLoaed");
});
</script>