1

Holla ,

this is the javascript im using

var timeoutID;

    function setup() {


            document.getElementById("demo").addEventListener("mousedown", resetTimer);


        startTimer();
    }
    setup();

    function startTimer() {

        timeoutID = window.setTimeout(goInactive, 1000);
    }

    function resetTimer() {
        window.clearTimeout(timeoutID);
        goActive();
    }

    function goInactive() {
        document.getElementById("demo").style.opacity = 0;
        document.getElementById("demo").style.transition = "1s";
    }

    function goActive() {
        document.getElementById("demo").style.opacity = 1;
        document.getElementById("demo").style.transition = "1s";

        startTimer();
    }   

everything is working fine , except i want it to go active only by left mouse button ( now right click left click and middle click are doing the job )

So many thanks in advance AliYous

2 Answers2

3

You have to detect the left mouse button press by checking the event object (Detect left mouse button press).

evt = evt || window.event;
if ("buttons" in evt) {
    return evt.buttons == 1;
}

And then if it's left mouse (1), proceed to do your job in resetTimer() function. Final code will be:

function resetTimer(e) {
    evt = e || window.event;
    if ("buttons" in evt) {
        if (evt.buttons == 1) {
            window.clearTimeout(timeoutID);
            goActive();
        }
    }
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

You can use the mouseup event on the element you want to use as the trigger. You haven't said what you click so I used document in the example below.

The below example is taken pretty much straight from the Mouse Event Button Documentation

document.addEventListener('mouseup', function(e) {
  var e = e || window.event;
  var btnCode;
  
  btnCode = e.button;

  switch (btnCode) {
    case 0:
      console.log('Left button clicked.');
      break;

    case 1:
      console.log('Middle button clicked.');
      break;

    case 2:
      console.log('Right button clicked.');
      break;

    default:
      console.log('Unexpected code: ' + btnCode);
  }
})

The short version more applicable to your scenario could look like the blow:

var resetTimer = function() {
  console.log('resetTimer called');
};

document.addEventListener('mouseup', function(e) {
  var e = e || window.event;
  var btnCode;

  btnCode = e.button;

  if (btnCode === 0) {
    resetTimer();
  }
})
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Nope
  • 22,147
  • 7
  • 47
  • 72