Sri Harsha Damarla
Sri Harsha Damarla

Reputation: 11

How to detect whether 2 buttons are clicked one after the another in javascript?

I've to trigger an alert when button #1 is clicked and then after the button 2# is clicked

if button 1# is clicked and immediately user is clicked on another button button x# then alert should not be trigger.

I've to track those 2 clicks that are one after the other so that i'll embed the js script in the google tag manager

Upvotes: 0

Views: 257

Answers (1)

Abelucho
Abelucho

Reputation: 240

This example will trigger an alert when Button 3 is clicked after Button 1.

var Last;
function getLast(t){
  if(Last=='btn1'&&t.id=='btn3')alert('btn1 then btn3')
  Last=t.id;
};
<button id='btn1' onclick='getLast(this);'>Button 1</button>
<button id='btn2' onclick='getLast(this);'>Button 2</button>
<button id='btn3' onclick='getLast(this);'>Button 3</button>

EDIT: with a timeout (like sugsested on comments), sequence must be done before 2 sec.

var Last,time;
function getLast(t){
  if(Last=='btn1'&&t.id=='btn3')alert('btn1 then btn3');
  Last=t.id;
  clearTimeout(time);
  time=setTimeout(function(){Last='';}, 2000);
};
<button id='btn1' onclick='getLast(this);'>Button 1</button>
<button id='btn2' onclick='getLast(this);'>Button 2</button>
<button id='btn3' onclick='getLast(this);'>Button 3</button>

Upvotes: 2

Related Questions