Daiaiai
Daiaiai

Reputation: 1089

Update function on click

I want to call a function which I call currently with each page-load ALSO with a click of the element #call-button. This is my current function:

window.addEventListener("load", function() {}

I hope a wrong solution clarifies a bit what I mean. So I am asking how to do that one here correctly:

window.addEventListener("load" || "#call-button.click" , function() {}

Upvotes: 2

Views: 1092

Answers (2)

karan3112
karan3112

Reputation: 1867

One way of doing it is bind the function to click of the element. And on window load trigger the element's click

document.getElementById('call-button').addEventListener('click', function() {
  alert('Called!!!');
});

function onLoad(){
  document.getElementById('call-button').click();
}
<body onload="onLoad()">
<button id="call-button">Click Me</button>
</body>

Upvotes: 3

William Karagozyan
William Karagozyan

Reputation: 48

This function isn't defined, it is bounded to the event.

You can either do a click listener on your element and copy the function part, or you can create the function and both your listeners will call the function.

Upvotes: 2

Related Questions