I am trying to link two JavaScript/jQuery events for two buttons. When one button is pressed, I want it wait for the second button to be clicked, then continue executing. Something like this:
$("#button1").on("click", function() {
// wait for button 2 to be clicked
console.log("Hello!");
});
Right now, the best way I’ve found to do this is to have a flag set by the second button and to poll until the flag changes:
let flag_triggered = false;
$("#button1").on("click", function() {
button_one_click();
});
function button_one_click(){
// wait for button 2 to be clicked
if(flag_triggered == false){
window.setTimeout(button_one_click, 100);
}else{
console.log("Hello!");
flag_triggered = false;
}
}
$("#button2").on("click", function() {
flag_triggered = true;
});
It feels like there must be a more reliable way to do this. How can I handle this situation?
3
Answers
There’s no need to poll, you can have the click on the second button directly execute the code you need to execute. There are at least two ways to do that:
Have the first button’s click add a one-off click handler to the second button that runs the code. In the normal case, adding an event handler inside an event handler is often a sign of a problem, but in this specific case it may be correct.
Have handlers on both buttons, with the first button’s click setting a flag, and the second button’s click looking at that flag to determine if it should run some code.
(A third option is to have a variable that you assign a function to, where the click on the second button runs the function if the variable has one and ignores it if the variable is
null
or similar, but that’s basically a variant of #1 above.)In both cases, you might consider providing the user some indication that the second button won’t do anything (for instance, by making it disabled), if in fact it won’t do anything until/unless the first button is clicked.
Since you don’t seem to want the second button to do anything until the first is clicked, #1 seems straightforward.
I should note that there’s no need for jQuery just to do something simple like this:
You can add the second button event listener when the first button is clicked. I would also note that you’re triggering a click event rather than listening for one.
try to do it this way
In this code, we use a flag button1Clicked to keep track of whether the first button has been clicked. When the first button is clicked, it sets button1Clicked to true and calls the waitForButton2 function. When the second button is clicked, it checks if button1Clicked is true, and if it is, it continues executing the desired code.
This approach ensures that the code after the second button click is only executed when the first button is clicked before the second button. If the second button is clicked without the first button, it provides a message indicating this.