JavaScript prevent touch move on body element, enable on other elements

technopeasant picture technopeasant · Dec 21, 2012 · Viewed 23.4k times · Source

but very simply, I'd like to prevent the touchmove event on the body element but leave it enabled for another element. I can disable fine... but I'm not sure how to re-enable it somewhere else!

I imagine that the below theoretically works because return true is the opposite of preventDefault, but it doesn't work for me. Might be 'cause $altNav element is in $bod?

JS:

$bod.bind('touchmove', function(event){

    event.preventDefault();
});
$altNav.bind('touchmove', function(event){

    return true;
});

Answer

Elias Van Ootegem picture Elias Van Ootegem · Dec 21, 2012

I'm not sure what lib you're actually using, but I'll asume jQuery (I'll also post the same code in browser-native-js if you're using something other than jQ)

$bod.delegate('*', 'touchstart',function(e)
{
    if ($(this) !== $altNav)
    {
        e.preventDefault();
        //and /or
        return false;
    }
    //current event target is $altNav, handle accordingly
});

That should take care of everything. The callback here deals with all touchmove events, and invokes the preventDefault method every time the event was triggered on an element other than $altNav.

In std browser-js, this code looks something like:

document.body.addEventListener('touchmove',function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    //in case $altNav is a class:
    if (!target.className.match(/\baltNav\b/))
    {
        e.returnValue = false;
        e.cancelBubble = true;
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        return false;//or return e, doesn't matter
    }
    //target is a reference to an $altNav element here, e is the event object, go mad
},false);

Now, if $altNav is an element with a particular id, just replace the target.className.match() thing with target.id === 'altNav' and so on...
Good luck, hope this helps