Khom Nazid
Khom Nazid

Reputation: 630

Copy to clipboard functionality making page jump to the bottom

I am using the CopyToClipboard functionality found on this site. Url in the comments in the code below. This works, but in Chrome/Brave/Opera browsers, it makes the page jump to the bottom. My own trigger for the code is also below. I'm trying to trigger this from a span, but having it as an a (link) element does the same thing. Page jumps to the bottom.

// Usage: copyToClipboard('some text')
// https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/69609643#69609643
 function copyToClipboard(text) {
    var doc = document;

    // Create temporary element
    var textarea = doc.createElement('textarea');
    textarea.style.position     = 'absolute';
    textarea.style.opacity      = '0';
    textarea.style.left         = "-9999px";
    textarea.textContent        = text;

    doc.body.appendChild(textarea);
    textarea.focus();
    textarea.setSelectionRange(0, textarea.value.length);

    // Copy the selection
    var success;
    try {
        success = doc.execCommand("copy");
    }
    catch(e) {
        success = false;
    }
    textarea.remove();
    return success;
}

My HTML that calls this function:

<span class="">
<span tabindex="0" class="uk-button"
onclick="copyToClipboard('URL_GOES_HERE')"
data-uk-tooltip="My tooltip content; ">     
<img src="SVG_ICON_HERE" width="20"/>
</span>  
</span>

Why is the JS making the page jump?

Upvotes: 0

Views: 176

Answers (1)

RoToRa
RoToRa

Reputation: 38431

It's probably because you are inserting a textarea and focusing it. Browsers scroll to input elements that get focus. And no that can't be stopped.

Use the modern clipboard API instead, as @vnm suggests: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard

Upvotes: 1

Related Questions