Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Touchscreen Press & Hold

I want the user to be able to touch and hold a button, and after a certain period of time, a function is called.

E.g. the button text starts as black, turns orange after 0.2s of pressing, and then green after 0.5s of pressing. If it is green, a function, myFunction(), is triggered.

I have made a start on it, more help would be appreciated. Thanks 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var btn = document.getElementById("pressBtn");

var pressedTime = 0;
var elaspedHoldTime;

btn.onmousedown = function() {
  if (pressedTime != 0) {
    pressedTime = performance.now();
  } else {
    elaspedHoldTime = performance.now() - pressedTime;
  }

  if (elaspedHoldTime > 200) {
    btn.style.color = "orange";
  }

  if (elaspedHoldTime > 1000) {
    btn.style.color = "green";
  }
};

btn.addEventListener("mouseup", function() {
  elaspedHoldTime = performance.now() - pressedTime;

  btn.style.color = "black";

  if (elaspedHoldTime > 500) {
    console.log("Call Function Here");
  }

  pressedTime = 0;
  elaspedHoldTime = 0;
});
<button id="btn">Button Text</button>

(It also has a bug for some reason)

>Solution :

You can use for that mousedown and setTimeout in Javascript

in setTimeout first arguement is what function must be run and second is when it should run,

in Javscript setTimeout 1000 is 1 second
in your case

0.5s = 500

0.2s = 200

I also used mouseup to back to normal the button styling

const btn = document.querySelector(".btn")

const triggerButton = () => {
  setTimeout(() => {
    btn.className = 'btn orange'
  }, 200)
  
  setTimeout(() => {
    btn.className = 'btn red'
    console.log("Triggered")
  }, 500)
  
}


btn.addEventListener("mouseup", () => {
  btn.className = 'btn'
})
btn.addEventListener("mousedown", triggerButton)
.btn.orange{
  background: orange;
}
.btn.red{
  background: red;
}
<button class="btn">Click</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading