Kamil
Kamil

Reputation: 13931

Button click event fires on page reload

I have problem with adding event to button element.

Problem:

Function supposed to be event handler fires on page reload and when I click button.

I want it to fire only when button is clicked.

This is my code:

index.html file:

<form id="contact_form">
    (Some form fields here)
    <button id="form_submit" value="send">Send</button>
</form>
<script src="contact_form.js"></script>

contact_form.js file:

var submit_button = document.getElementById('form_submit');

submit_button.addEventListener("click", test_click_event());

function test_click_event()
{
     alert("Button clicked");
}

I'm using Chrome to debug.

Upvotes: 2

Views: 5863

Answers (3)

adi
adi

Reputation: 31

You can keep the brackets but you need to add an anonymous function. See here: https://www.w3schools.com/jsref/met_document_addeventlistener.asp

For example:

submit_button.addEventListener("click", function (){
    test_click_event();
});

Upvotes: 1

Vadim S
Vadim S

Reputation: 358

submit_button.addEventListener("click", test_click_event);

brackets are not needed

Upvotes: 4

Alex Kneller
Alex Kneller

Reputation: 413

() brackets call to function execute remove them or use this:

var submit_button = document.getElementById('form_submit');

    submit_button.addEventListener("click", function(){test_click_event();});

    function test_click_event()
    {
         alert("Button clicked");
    }

Demo

Upvotes: 1

Related Questions