title: Copy to Clipboard JS function causing keyboard to open and scroll to top on mobile
body: <p>In my rails app, I have an event listener on a "copy to clipboard" icon. When that's clicked, I call a function which creates a textarea, selects it, and copies it using document.execCommand("copy").</p>
  
  <p>Everything works great on desktop, but on mobile - clicking the icon scrolls to the top of the page and opens the keyboard.</p>
  
  <p>How do I avoid this?</p>
  
  <pre><code>  // copies shareable url
  
    $('body').on('click', '.clipboard', function(e){
      e.preventDefault();
      var url = $(this).closest('.trailer').find('.shareable-url')
      copyToClipboard(url)
    });
  
  
  //  copy to Clipboard
  
  function copyToClipboard(elem) {
  
      // create hidden text element, if it doesn't already exist
      var targetId = "_hiddenCopyText_";
      var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
      var origSelectionStart, origSelectionEnd;
      if (isInput) {
          // can just use the original source element for the selection and copy
          target = elem;
          origSelectionStart = elem.selectionStart;
          origSelectionEnd = elem.selectionEnd;
      } else {
          // must use a temporary form element for the selection and copy
          target = document.getElementById(targetId);
          if (!target) {
              var target = document.createElement("textarea");
              target.style.position = "absolute";
              target.style.left = "-9999px";
              target.style.top = "0";
              target.id = targetId;
              document.body.appendChild(target);
          }
          target.textContent = elem.val();
      }
      // select the content
      var currentFocus = document.activeElement;
      var x = window.scrollX, y = window.scrollY;
      target.focus();
      window.scrollTo(x, y);
      target.setSelectionRange(0, target.value.length);
  
      // copy the selection
      var succeed;
      try {
          succeed = document.execCommand("copy");
      } catch(e) {
          succeed = false;
      }
      // restore original focus
      if (currentFocus &amp;&amp; typeof currentFocus.focus === "function") {
          currentFocus.focus();
      }
  
      if (isInput) {
          // restore prior selection
          elem.setSelectionRange(origSelectionStart, origSelectionEnd);
      } else {
          // clear temporary content
          target.textContent = "";
      }
      return succeed;
  }
  </code></pre>