skip to Main Content

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


  1. 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:

    1. 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.

    2. 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.

    const button1 = $("input[value='Button 1']");
    const button2 = $("input[value='Button 2']");
    
    button1.on("click", () => {
        button2.prop("disabled", false);
        button2.one("click", () => { // <== Note 'one' rather than 'on'
            console.log("Button 2 clicked after Button 1");
            button2.prop("disabled", true);
        });
    });
    <input type="button" value="Button 1">
    <input type="button" value="Button 2" disabled>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    I should note that there’s no need for jQuery just to do something simple like this:

    const button1 = document.querySelector("input[value='Button 1']");
    const button2 = document.querySelector("input[value='Button 2']");
    
    button1.addEventListener("click", () => {
        button2.disabled = false;
        button2.addEventListener(
            "click",
            () => {
                console.log("Button 2 clicked after Button 1");
                button2.disabled = true;
            },
            { once: true } // <== Removes the handler on first call
        );
    });
    <input type="button" value="Button 1">
    <input type="button" value="Button 2" disabled>
    Login or Signup to reply.
  2. 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.

    
    let btn1 = $(...),
        btn2 = $(...);
    
    function btn2handler(evt) {
      console.log(evt);
    }
    
    btn1.on('click', () => {
      let evts = $._data(btn2[0],'events');
      if(evts.click) {
        // If btn2 event handler set up, remove it
        btn2.off('click', btn2handler);
      }
      else {
        // otherwise add it
        btn2.on('click', btn2handler);
      }
    })
    
    
    Login or Signup to reply.
  3. try to do it this way

    $(document).ready(function() {
        var button1Clicked = false; // Flag to track if button 1 is clicked
        
        // Event handler for button 1
        $("#button1").on("click", function() {
            button1Clicked = true;
            console.log("Button 1 clicked");
            waitForButton2();
        });
    
        // Event handler for button 2
        $("#button2").on("click", function() {
            if (button1Clicked) {
                console.log("Button 2 clicked");
                // Continue with your code after button 2 is clicked
                console.log("Hello!");
            } else {
                console.log("Button 2 clicked without button 1");
            }
        });
    
        // Function to wait for button 2
        function waitForButton2() {
            if (!button1Clicked) {
                console.log("Waiting for button 2...");
            } else {
                console.log("Button 2 was clicked before button 1.");
            }
        }
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search