Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener function works at the beginning without being fired [duplicate]

So here are my HTML codes:

document.getElementById("sub").addEventListener("click", testing());
function testing() {
 document.getElementById("demo").innerHTML ="good"; 
}
<input type="submit" value="Place Order" id="sub"/>
    </fieldset> </form>
    <p id="demo"></p>
    <script type="text/javascript" src="Q4.js"></script>

In which I declared a button to submit the form. I added an event to the submit button to run the function testing(). I expected that when the user clicks on the button submit, the page will prompt "good". But, as soon as I load the page, "good" already appeared without clicking in the button. result page

Why does this happen?

like image 821
aNaN Avatar asked Dec 12 '25 07:12

aNaN


1 Answers

You should remove parentheses to prevent function testing() to be executed. Just put the name of the function.

You can find more details and simple example of listener here.

Here is a working snippet :

/*file javaScript Q4.js*/
document.getElementById("sub").addEventListener("click", testing);
function testing() {
document.getElementById("demo").innerHTML ="good"; }
<input type="submit" value="Place Order" id="sub"/>
</fieldset> </form>
<p id="demo"></p>
<script type="text/javascript" src="Q4.js"></script>

You can also put your function directly into your listener, like this :

document.getElementById("sub").addEventListener("click", function() {
    document.getElementById("demo").innerHTML="good"; 
});

About the bug that "show the good word for a second only" : Clicking the button causes the form to be submitted, which means the page reloads or the loads the URL in action. That means that all temporary changes that JavaScript made in the current page load are gone. Thanks Felix Kling

like image 51
André DS Avatar answered Dec 13 '25 20:12

André DS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!