• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript function run without being called


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!

var subBtn = document.getElementById('submit');      //submit button       
subBtn.addEventListener('mouseup',mup );          //release click on submit button
function mup(){               

function getRandomNumber() {                     //normally genertates random number
    alert("Got random#");

document.addEventListener("DOMContentLoaded", (event) =>     //runs after page fully loaded
Is the submit button in a form? If so, it could be that pressing the submit button causes a page reload, which calls the `DOMContentLoaded` event to fire a second time.
What happens when you use the `once` option?

document.addEventListener("DOMContentLoaded", (event) =>     //runs after page fully loaded
}, {once: true});
Ok, removed the form, now works as expected.
Darn, did not know about that behavior with the form but I am really new to this.
Thanks bud, been scratching my head for a night over this.

New Threads

Latest posts

Buy us a coffee!

Top Bottom