简体   繁体   中英

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.

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

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

this part of your code means that if you are clicking the buttons both at the same time which is not possible for a human. also if you want to check conditions of variables, you should check all of them. I mean

click.onclick === true && click2.onclick === true

in your code, you are checking if click.onClick is truthy and click2.onclick is absolutely equal to true.

you can define a variable and increase its value or set true/false, if they are both clicked then you can run your other code.

let button1 = 0;
let button2= 0;

click.onclick = function() {
   button1++
   }
}

click2.onclick = function() {
button2++
  }
}

if (button1 > 0 and button2 > 0) {
   console.log("You have clicked on both buttons");
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM