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

23,857

Solution 1

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

Solution 2

Use a custom CSS class and test for it in the document handler, eg:

<div>
    This div and its parents cannot be scrolled.
    <div class="touch-moveable">
        This div and its children can.
    </div>
</div>

then:

jQuery( document ).on( 'touchmove', function( ev )
{
    if (!jQuery( ev.target ).parents().hasClass( 'touch-moveable' ))
    {
         ev.preventDefault();
    }
});

http://tinyurl.com/mo6vwrq

Solution 3

you can add a argument,like this

$bod.bind('touchmove', function(event,enable){
   if(enable){
       event.preventDefault();
   }

});
Share:
23,857
technopeasant
Author by

technopeasant

Asking obvious questions.

Updated on August 16, 2020

Comments

  • technopeasant
    technopeasant almost 4 years

    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;
    });