Reputation: 1183
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.
Upvotes: 0
Views: 65
Reputation: 1130
Let me start by explaining why your last two examples do not work:
my_button.onclick = click_button(my_button.value);
This will execute the click_button()
function right away, and will assign whatever the function returns to my_button.onclick
my_button.onclick = "click_button(my_button.value);";
This just sets the value of my_button.onclick
to a string. The button's onclick property is not expecting a string with javascript code inside, and it will not evaluate it in that way.
You can see how the onclick
property works here:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick
The function assigned to onclick
will be passed a MouseEvent
. Your click_button
function takes a value as a parameter, so as of right now you can't simply assign the function itself to onclick
like so:
my_button.onclick = click_button // won't be given my_button.value
because the value passed to be will be a MouseEvent
, not what you expect.
If you modify the click_button
function to not require the value parameter, then you could do something like:
function click_button () {
// Do stuff using this.value or my_button.value directly
}
my_button.onclick = click_button
Otherwise, if you want to be able to pass my_button.value
to the function, you need to wrap it in another function, as you do correctly in the first example.
As @Mikey pointed out in the comments, you can get the value by using this.value
inside of the function. The MDN docs state that this
will be set to the element within the function.
Upvotes: 1
Reputation: 558
In the first example, you assign a reference to a function that should be called when the button is clicked. This is correct.
In the second example, you assign the result of the click_button function to the onclick. So when your code is read by the engine, it executes your click_button function and assigns the resulting value to the onclick. So when you click your button, there is no function to execute, just a value.
In the third example you just assign a string to your onclick. This can't work.
So yes the first way is the correct way.
Upvotes: 2