Html copy text button

How to copy text from a div to clipboard

I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work. After trying I got to:

    
Click to copy

Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)

For some reason document.createRange() didn’t work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0) .

This should be the top answer in this thread. After several hours of finding one workable solution, this finally worked for me. Thanks. 🙂

Tip: add another window.getSelection().removeAllRanges(); after the copy command to deselect the content after it is copied.

This is simplified example of using Range based selections, it doesn’t intend to cover all corner cases. And is mainly showcasing one of the ways to use the Range class. Can you be more specific or post another question with your exact use case? I have myself used Range based Selection s with multiple divs / element s . I would highly advise to check on the Range API and see if any of the other functions this provides would help.

Читайте также:  Увеличение при наведении javascript

@FarhanBinAmin check Range.setStart() and Range.setEnd() . and use those instead of Range.selectNode()

Источник

Copy Text to clipboard using HTML button [duplicate]

How do I actually copy some fixed text to clipboard using javascript? This is my code and it’s not working maybe there’s another way and I don’t know.

I want to copy some fixed text using just button, so I don’t have to select texts manually and copy them. Thanks.

What text are you trying to copy? Please see how to create a minimal,reproducible example so we can see the problem you are having and be able to help.

@FluffyKitten I believe there is a minimal example above. «Some text here» is not being copied to the clipboard as expected.

I was trying to copy some text that are hidden from a user’s input and interface so i do not have to select them manually thanks.

3 Answers 3

You can try this approach:

var copy_text_val = document.querySelector('.copy_text'); function Copy()

For this action you have to select the text dynamically before actually copying it: Here is an example:

function copy_text(node) < if(document.body.createTextRange)< const range = document.body.createTextRange(); range.moveToElementText(node); range.select(); document.execCommand('copy'); >else if(window.getSelection) < const selection = window.getSelection(); const range = document.createRange(); range.selectNodeContents(node); selection.removeAllRanges(); selection.addRange(range); document.execCommand('copy'); >else < console.warn("Could not select text in node"); >> // This copy_text function ensures cross-browser compatibility // What it does is select the text within the range of the node holding the text // Then executes the "copy" command on that selected text function clear_selection() < if(window.getSelection)< window.getSelection().removeAllRanges(); >else if(document.selection) < document.selection.empty(); >> // This clear_selection function clears any selection from the document document.addEventListener("DOMContentLoaded", function() < document.getElementById("clipboard-exec").onclick = function()< copy_text(document.getElementById("clipboard-text")); // Copy the text on clicking the button setTimeout(() =>< clear_selection() >, 500); // Clear the selection after 0.5s > >);
This is the text that will be copied to your clipboard when you click on the "Copy" button. 

Of course with this function you can just restructure it to fit your needs. Also note that what you are trying to accomplish by copying directly to the keyboard without a valid text node actually holding the text won’t work, I guess for security purposes

But you can create a node in the document with the text but hide it from view then select it using this function .. NOTE the text you are copying to the clipboard has to be actually in the document, for you to execute the «copy» command on it

Источник

Скопировать текст в буфер обмена нажатием на кнопку

Задача простая — копировать текст из какого-то блока нажатием кнопки, например, это может быть код купона или ссылка на статью в конце самой статьи. Согласитесь — довольно таки удобно, вместо выделения и копирования просто нажать одну кнопку и нужный текст уже в буфере обмена.

Самый простой и примитивный HTML для примера:

 
Чтобы не загружать мозг лишним кодом, в CSS будет только одно правило для скрытия сообщения об удачном копировании:

Ну и самая главная часть — скрипт, который выполнит всю работу:

$(function() < // copy content to clipboard function copyToClipboard(element) < var $temp = $(""); $("body").append($temp); $temp.val($(element).text()).select(); document.execCommand("copy"); $temp.remove(); > // copy coupone code to clipboard $(".coupon-btn").on("click", function() < copyToClipboard("#coupon-field"); $(".coupon-alert").fadeIn("slow"); >); >);

Думаю, сильно подробно разбирать код нет смысла. Но в двух словах:

Функция copyToClipboard(element) скопирует в буфер содержимое заданного блока.

Копирование произойдет при нажатии на кнопку «.coupon-btn» .

copyToClipboard(«#coupon-field») — вызываем функцию copyToClipboard(element) и указываем, что нужно скопировать содержимое блока #coupon-field .

$(«.coupon-alert»).fadeIn(«slow»); — после копирования показываем сообщение, что что-то произошло и содержимое блока скопировано.

Ниже рабочий пример, в котором так же добавлено поле, чтобы вставить в него содержимое из буфера и проверить работоспособность кода:

Простая валидация email с помощью javaScript. Суть в том, чтобы не дать отправить форму, пока…

Рассмотрим 2 наиболее часто применяющихся примера. Для обоих примеров будет общий HTML: И общие правила…

Простой пример, как убрать стрелки в поле input[type=»number»] с помощью CSS: Важное дополнение: по прежнему…

Часто в мобильной версии сайта используется кнопка типа «бургера» для вызова основного меню сайта. На…

Источник

How to Copy Text to the Clipboard with HTML and JavaScript

Having a click-able button on your website that allows users to copy text can be easily achieved by using the document.execCommand() method.

Unfortunately support for the execCommand() method is lacking in many old browsers, such as Opera Mini and the UC Browser for Android.

The vast majority of users should be able to copy the text with out any issues and the website can display an error message if the copy command fails.

Additionally to work around browser support problem: As long as we put the text into a text box, it should be easy enough for users using these browsers to manually copy the text to the clipboard.

Copying Text From a Text Box to the Clipboard Using JavaScript

Demo:

HTML Code

JavaScript Code

After pressing the button, you should be able to paste the text into the text field below or in any other application that will accept text being pasted from the clipboard.

Here is a box that you can paste the text into so you don’t have to leave this page:

Unfortunately, due to security concerns, it is not possible to paste text using JavaScript into a browser window through JavaScript, unless it’s a background page of a browser extension. This is to prevent websites from gathering sensitive information such as user passwords.

There is also one big issue with this code, if the user currently has text selected, they will lose their selection. In the following examples, the code will restore the user’s previous text selection if they had one.

How to Copy Any Text By Creating a Selection Range in JavaScript

Since selecting all of the text in a text box using select() will only work with a text box, if you want to copy all text to the clipboard of a specific ID or class name, you will have to create a text selection range instead.

This is a little bit more flexible as you do not have to have a text box.

Demo:

HTML Code

The text to copy to the clipboard.

Javascript Code

  

How to Copy Text To the Clipboard that Isn’t Visible with HTML

This is probably the most useful version of the script as it allows you to generate text in JavaScript, which is not visible on the page at all, then place that text on to the clipboard.

It works by creating an element that is off the screen with the text that is to be copied.

Since browser compatibility could be an issue, the script will also display an error message in a message box if it can’t copy the text. Using a message box isn’t the best way to handle this but you can customize the code to display the error notification any way you choose.

Demo:

Copy Some Text That You Can’t See!

HTML Code

JavaScript Code

  

I really hope that you enjoyed this tutorial!

Read More From Actual Wizard

An email address has four parts; the recipient name, the @ symbol, the domain name, and the top-level domain. …

There are a number of different ways to get the last element of an array in JavaScript. Below we will explore …

How to use document.write() in JavaScript The document.write() function is commonly used when testing simple …

Opening a new browser window in a new tab can be done easily in JavaScript. Modern web browsers provide a …

Primary Sidebar

Copyright © 2023 ActualWizard.com

Источник

How TO — Copy Text to Clipboard

Learn how to copy text to the clipboard with JavaScript.

Click on the button to copy the text from the text field.

Copy Text to Clipboard

Step 1) Add HTML:

Example

Step 2) Add JavaScript:

Example

function myFunction() <
// Get the text field
var copyText = document.getElementById(«myInput»);

// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices

// Copy the text inside the text field
navigator.clipboard.writeText(copyText.value);

// Alert the copied text
alert(«Copied the text: » + copyText.value);
>

Display Copied Text in a Tooltip

Example

.tooltip <
position: relative;
display: inline-block;
>

.tooltip .tooltiptext visibility: hidden;
width: 140px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -75px;
opacity: 0;
transition: opacity 0.3s;
>

.tooltip .tooltiptext::after content: «»;
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
>

.tooltip:hover .tooltiptext visibility: visible;
opacity: 1;
>

Источник

Оцените статью