For something to happen when the user clicks, you must add an event handler (or callback function) to the element in question. That is done with the .addEventListener()
method of the element:
// Get a reference to the button
let btn = document.getElementById("b1");
// Add an event handler for the click event
btn.addEventListener("click", myFunction);
function myFunction(){
alert('Hello');
}
<button id='b1'>Click on button</button>
FYI: There is a much older way of doing this that you will still see people use today because they don’t fully understand how event handlers work. That way uses embedded event attributes in the HTML, like onclick
. Do not use these!
3
solved How to interact my button with my function