Mouseup and mousedown not working on ios

2.6k views Asked by At

So I need something like the following, it's basically a 2-dir touchpad that the user touches (and holds the touch) with his finger to move the character a certain way. This works fine on my PC, but it doesn't seem to work when I test it on iOS. The reason being, is probably because there is not mouse, so mousedown and mouseup don't work. Are there any alternatives? I've tried to use keydown and keyup but those didn't work either.

Here's my code:

var $div = $('#character');

$('#ios-left').mousedown(function(){
   leftTimer = setInterval(function(){
    processWalk('left');
    },100);
}).mouseup(function(){
    $('#character').stop();
    clearInterval(leftTimer);
});
$('#ios-right').mousedown(function(){
        rightTimer = setInterval(function(){
     processWalk('right');
             },100);
}).mouseup(function(){
    $('#character').stop();
    clearInterval(rightTimer);
});

Thanks! (Keep in mind that I need the user to hold the div down with his finger to have the character move and when he releases his finger, the character should stop)

EDIT: Link to my question: JQuery Mouseup on iOS

1

There are 1 answers

6
Koti Panga On BEST ANSWER

Use very lite weight jquery.mouse2touch.min.js plug-in to simulate mouse events for touch events.

Apply mouse event handler behavior to touch events like below $("#elmentID").mouse2touch() OR $(".elment-css-class").mouse2touch() which will do the job to copy all mouse based functionality to touch.

In your code you can call mouse2touch() like below:

$('#ios-left').mousedown(function(){
   leftTimer = setInterval(function(){
    processWalk('left');
    },100);
}).mouseup(function(){
    $('#character').stop();
    clearInterval(leftTimer);
}).mouse2touch();

$('#ios-right').mousedown(function(){
        rightTimer = setInterval(function(){
     processWalk('right');
             },100);
}).mouseup(function(){
    $('#character').stop();
    clearInterval(rightTimer);
}).mouse2touch();

EDIT: For another linked Question and here I'm providing same answer.

Working Fiddle

The issue with timer, you should clear-time-interval before move. Your global variable TimerWalk with clearInterval(TimerWalk); should be useful.

Here is the code block

$('#ios-left').mousedown(function () {
    clearInterval(TimerWalk);
    TimerWalk = setInterval(function () {
        processWalk('left');
    }, 100);
}).mouseup(function () {
    $div.stop();
    clearInterval(TimerWalk);
}).mouse2touch();

$('#ios-right').mousedown(function () {
    clearInterval(TimerWalk);
    TimerWalk = setInterval(function () {
        processWalk('right');
    }, 100);
}).mouseup(function () {
    $div.stop();
    clearInterval(TimerWalk);
}).mouse2touch();

This is only fix for proper movement, you may need to address other issues.