Ask coding questions

← Back to all posts
Javascript onclick Event
Smart0ne (725)

How do I make it such that whenever the user clicks the button, the add function is called (without using the onclick attribute of the button)?

Answered by IntellectualGuy (693) [earned 5 cycles]
View Answer
Comments
hotnewtop
IntellectualGuy (693)

Use event listeners

document.querySelector('button').addEventListener('click',add);
Smart0ne (725)

@IntellectualGuy Thank you. However, I have a question. What's the difference between document.querySelector and document.getElementById? Whenever I try the latter, it doesn't work.

IntellectualGuy (693)

@Smart0ne
here's an stack overflow question to help.

And here's how you would do it using the getElementById

document.getElementById('button_plus').addEventListener('click',add);

So you basically have to just pass in the id of the element you want to select(Without the #)