javascriptdomonclickxapi

How do I combine 2 onclick functions in javascript?


Hi there I am trying to combine 2 javascript onClick function so that they only fire once both have been clicked, this is what I have currently attempted.

Javascript

click.onclick = function() {
   for (let i = 0; i < 1; i++) {
       console.log("Clicks counted " + I);
   }
}

click2.onclick = function() {
  for (let i = 0; i < 1; i++) {
      console.log("Clicks counted " + I);
  }
}

if (click.onclick && click2.onclick === true) {
   console.log("You have clicked on both onClicks");
}

HTML

<section>
    <button id="button-click">Nice</button>
    <button id="button-click-2">Even nicer</button>
</section>

Super simple I know, but I just wanted to figure out how to do this as it's for an API call so requires both buttons to be clicked and then send a statement.


Solution

  • You could use a function which checks a value. This value is made up by using bitwise or with 1 or 2, for more buttons double the value for each one.

    In the checking function, check the value which is 2n - 1, for two check against 3.

    let clickButtons = 0;
    
    function check() {
        if (clickButtons === 3) console.log("You have clicked on both onClicks");
    }
    
    document.getElementById("button-click").addEventListener('click', function() {
       clickButtons |= 1;
       check();
    });
    
    document.getElementById("button-click-2").addEventListener('click', function() {
       clickButtons |= 2;
       check();
    });
    <section>
        <button id="button-click">Nice</button>
        <button id="button-click-2">Even nicer</button>
    </section>