Reputation: 51
I have two buttons, both of which trigger a function to run when clicked, but with different parameters. They should only trigger that function when they are clicked while a specific element on the page exists.
JS code:
if (pageExists != null) {
document.getElementById('button1').onclick = function(53);
document.getElementById('button2').onclick = function(23);
}
Button html (They are identical copies other than ID):
<a href="nextpage.html"><button type="button" id="button1">click here</button></a>
The function it calls stores that parameter in LocalStorage, and then it should go to the next page using html code. Using breakpoints shows that it stores 53, then 23, as soon as the page loads. The capitalization and ID's are correct.
What can I do to make it wait until one of the two buttons are clicked before executing the function? I can't use jquery for this.
Upvotes: 1
Views: 4322
Reputation: 628
You are calling the function instead of setting the function to be called, so when your code is run to set up the event handlers, they run function(53)
and then set the handler to the return value of that function call, which is invalid. Instead, you want to set it to a function. Try this:
if (pageExists != null) {
document.getElementById('button1').onclick = function.bind(53);
document.getElementById('button2').onclick = function.bind(23);
}
If you can't use .bind
due to compatibility reasons (this will also explain it better):
if (pageExists != null) {
document.getElementById('button1').onclick = function() {
function(53);
};
document.getElementById('button2').onclick = function() {
function(23);
};
}
Note that I'm assuming that your function isn't actually called function
, as that's a reserved keyword.
Upvotes: 5