Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally block scrolling/touchmove event in mobile safari

iOS 5 now allows native overflow: scroll support.

What I'd like to do is disable the touchmove event for everything except elements that have the 'scrollable' class or their children.

But I can't seem to get it to work; this is what I've been working with below:

<html>
<head>
<style>
.scrollable {
 height: 5em;
 overflow-y: scroll;
 -webkit-overflow-scrolling: touch;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>

// doesn't seem to work
var handleMove = function (e) {
  if (!$(e.target).parents().andSelf().hasClass('scrollable')) {
    e.preventDefault();
  }
};

document.addEventListener('touchmove', handleMove, true);

</script>
</head>
<body>
<div>
don't scroll if you drag here
</div>
<div class='scrollable'>
should be scrollable if you drag here
<ul>
<li>and here</li>
<li>and here</li>
<li>and here</li>
<li>and here</li>
<li>and here</li>
<li>and here</li>
<li>and here</li>
<li>and here</li>
</ul>
</div>
don't scroll if you drag here
</body>
</html>
like image 757
ʞɔıu Avatar asked Dec 22 '11 22:12

ʞɔıu


1 Answers

I know it's been a while since you asked the question, but I had the same issue and I used your code as the basis for solving the problem. So thanks for the inspiration.

(Javascript + jQuery)

<script>
var handleMove = function (e) {
    var scrollable = false;
    var items = $(e.target).parents();
    $(items).each(function(i,o) {
        if($(o).hasClass("scrollable")) {
            scrollable = true;
        }
    });
    if(!scrollable)
        e.preventDefault();
};
document.addEventListener('touchmove', handleMove, true);
</script>

Or less verbose, but ultimately the same result (credit J Griffiths):

<script>
var handleMove = function (e) {
    if($(e.target).closest('.scrollable').length == 0) { e.preventDefault(); }
}
document.addEventListener('touchmove', handleMove, true);
</script>

You should also include the following META tag.

<meta name="viewport" content="width=device-width, initial-scale=1.0,
  maximum-scale=1.0, user-scalable=no;" />
like image 70
Scott Avatar answered Sep 28 '22 08:09

Scott