Nerks
Nerks

Reputation: 61

Run JavaScript function for every two times a button is clicked

For my web app, I need some javascript code which will run every two times a button is clicked. I've tried so many different things but I can't quite get it right. Because I'm a rookie coder I can't get any code demos on what I've done but I would really appreciate your help anyways.

Upvotes: 0

Views: 1471

Answers (4)

Pedro Sturmer
Pedro Sturmer

Reputation: 604

Well you can do that:

var clicked = 0;

function myFunction() {

  clicked++;

  console.log(clicked)
  
  if (clicked === 2) {
    alert('i like cats');
    clicked = 0;
  };

};
<button onclick="myFunction()">click me twice!</button>

Upvotes: 0

Fobos
Fobos

Reputation: 1166

Try this

<button onclick="clickFunction()">click me twice!</button>

<script>
var eventClick = 0;

function clickFunction() {
  eventClick++;  
  if (eventClick === 2) {
    alert('Clicked');
    eventClick = 0;
  };

};
</script>

Upvotes: 0

alt255
alt255

Reputation: 3576

Here is one way to do it. Replace the action method with your custom method

<button onclick="clicked()">Click Me</button>

function action() {
  console.log('Do something here')
}
var counter = 0;
function clicked() {
  if (counter === 2) {
    action();
    counter = 0;
  }
  counter++;
}
<button onclick="clicked()">Click Me</button>

Upvotes: 0

ggorlen
ggorlen

Reputation: 57394

Here's a simple approach using an index to keep track of even/oddness:

const fn = e => outElem.innerHTML += "clicked!<br>";
const outElem = document.getElementById("output");
let i = 0;

document.getElementById("btn").addEventListener("click", e => i++ & 1 ? fn(e) : false);
<button id="btn">click</button>
<div id="output"></div>

Upvotes: 1

Related Questions