Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • 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

noweare

Coder
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!

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>
 
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?

JavaScript:
document.addEventListener("DOMContentLoaded", (event) =>     //runs after page fully loaded
    getRandomNumber();
    alert("DomContentLoaed");
}, {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!

Back
Top Bottom