How to stop focus() in custom js from scrolling to footer?

Question

I’m using a js to create a "copy to clipboard" button, using the following code from here:

function copy(selector){
  var $temp = $("<div>");
  $("body").append($temp);
  $temp.attr("contenteditable", true)
       .html($(selector).html()).select()
       .on("focus", function() { document.execCommand('selectAll',false,null); })
       .focus();
  document.execCommand("copy");
  $temp.remove();
}

I then load the script using the following:

add_action( 'wp_enqueue_scripts', 'load_copy' );
function load_copy() {
    wp_enqueue_script('copyjs', get_template_directory_uri() . '/js/copy.js', array('jquery') );
}

I then have a button setup to trigger this js onclick, to copy text from within a div element. The function works beautifully, except: because the js is loaded in the footer in WP, the focus() command causes the page to scroll to the bottom when the onclick event is triggered.

I’ve tried using focus({preventScroll: true}) but then the function doesn’t work, and I’m not savvy enough with js to figure out why.

Does anyone have a solution to stop the page from scrolling?

Current page I’m testing this on is here (use the blue button): https://dev.universaltheosophy.com/contribute/

0
Jon Fergus 8 months 2020-12-11T18:10:27-05:00 0 Answers 14 views 0

Leave an answer

Browse
Browse