0

Is it possible to make a button be able to have a long button press on iOS? I have searched all over and not found any solutions for this problem. At first if you long press a button it will try to select it (for copying). Using some CSS, I disabled this, but it still doesn't register a long button press. I think it is because the possibility that you might be scrolling the page that it does not long press in the first place. The purpose of this is that I want the button to disappear on a long press.

Here is a JSFiddle that works on PC, but doesn't on my iPhone (there is a div commented out because it doesn't matter if the long press is on a div or button, I can create an artificial button using a div): http://jsfiddle.net/ynkLmz5n/3/

Thanks in advance.

var MenuToggle = document.getElementsByClassName("hide")[0];
MenuToggle.style["-webkit-user-select"] = "none";
MenuToggle.addEventListener("mousedown", Vanish);
MenuToggle.addEventListener("mouseup", VanishClear);
var timer;
function Vanish() {
    longpress = false;
    timer = setTimeout(function() {
        MenuToggle.style.display = "none";
    }, 1000);
}
function VanishClear() {
    clearTimeout(timer);
}
MathMan08
  • 59
  • 1
  • 10
  • This question http://stackoverflow.com/questions/2625210/long-press-in-javascript has what you asked but seems noone cared to test that on iOS it seems. Maybe you can try convert https://github.com/pisi/Longclick into vanilla JS like you are using, looks like that one works. – RaphaelDDL Sep 10 '14 at 18:17

2 Answers2

3

Have you tried using touch events?

var timer

MenuToggle.addEventListener('touchstart', function() {
  timer = setTimeout(function() {
    MenuToggle.style.display = 'none'
  }, 1000)
}, false)

MenuToggle.addEventListener('touchend', function() {
  clearTimeout(timer)
}, false)
Daryl Ginn
  • 1,394
  • 9
  • 14
1

You'll want to use touch events (touchstart and touchend) in place of mouse events.

Here's an updated fiddle: http://jsfiddle.net/ynkLmz5n/4/

MenuToggle.addEventListener("touchstart", Vanish);
MenuToggle.addEventListener("touchend", VanishClear);

Also, if you're looking to add touch interaction, I'd recommend hammer.js. It's a great touch library that includes support for things like Press)

Project page: http://hammerjs.github.io/

Press event documentation: http://hammerjs.github.io/recognizer-press/

Jack
  • 9,151
  • 2
  • 32
  • 44