I'm creating some simple buttons on a web page using Javascript and need to call a function when they are clicked. I've come up with the following example that works based on searching for answers. However, it seems wrong to create a function just to call a function. I wasn't able to successfully directly call the function "click_button" which is elsewhere in the script any other way.
This works:
my_button.onclick = function (){
click_button(my_button.value);
}
These don't work:
// This executes on first run, but not when clicked.
my_button.onclick = click_button(my_button.value);
// This doesn't do anything when clicked.
my_button.onclick = "click_button(my_button.value);";
Is the top example the proper way to call a function from a button click in JavaScript?
Thanks for any help.
my_button.addEventListener("click", myScript);look at thisonclickshould becallback(function)to work when triggered / fired.