Search code examples
javascripthtmllong-press

Disable long press on smartphone


I have already had a usable code for disabling long press but now I don't want to get element by ID. It's not possible for me to add Id for every particular items. I want to make it works for every img in a Name Tag. However, it's not working now. Please help.

Original working line: preventLongPressMenu(document.getElementById('theimage'));

Edited line: preventLongPressMenu(document.getElementByTagName('body img'));

entire code:

<!DOCTYPE html>
<html>
<head>
  <script>
    function absorbEvent_(event) {
      var e = event || window.event;
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      e.cancelBubble = true;
      e.returnValue = false;
      return false;
    }

    function preventLongPressMenu(node) {
      node.ontouchstart = absorbEvent_;
      node.ontouchmove = absorbEvent_;
      node.ontouchend = absorbEvent_;
      node.ontouchcancel = absorbEvent_;
    }

    function init() {
      preventLongPressMenu(document.getElementByTagName('body img'));
    }
  </script>
  <style>
    *:not(input):not(textarea) {
    -webkit-user-select: none; /* disable selection/Copy of UIWebView */
        -webkit-touch-callout: none; /* disable the IOS popup when long-press on a link */

    }
  </style>
</head>
<body onload="init()" id="theimage" >
  <img src="http://www.google.com/logos/arthurboyd2010-hp.jpg" width="400">
</body>
</html>

Solution

  • You are misspelling the method name, and not passing the correct string. It's getElementsByTagName (note the s on elements), and you just pass the name of the tag not a css selector. You will also have to modify the function to loop over the result since it will be a nodelist

    preventLongPressMenu(document.getElementsByTagName('img'));
    
    function preventLongPressMenu(nodes) {
      for(var i=0; i<nodes.length; i++){
         nodes[i].ontouchstart = absorbEvent_;
         nodes[i].ontouchmove = absorbEvent_;
         nodes[i].ontouchend = absorbEvent_;
         nodes[i].ontouchcancel = absorbEvent_;
      }
    }
    

    If the browser on the phone supports it you can also use querySelector/querySelectorAll, which allows you to use css selectors to select elements

    preventLongPressMenu(document.querySelectorAll('body img'));
    
    function preventLongPressMenu(nodes) {
      for(var i=0; i<nodes.length; i++){
         nodes[i].ontouchstart = absorbEvent_;
         nodes[i].ontouchmove = absorbEvent_;
         nodes[i].ontouchend = absorbEvent_;
         nodes[i].ontouchcancel = absorbEvent_;
      }
    }