Copy text by clicking on a DIV

Asked

Viewed 5,296 times

1

How do I, with Jquery preference, when clicking the ola class div:

$('ola').click(function(){
   //FUNÇÃO DE COPIAR AQUI
});

Does it copy a text? For example, by clicking on the ola class div, it copy the text "hello world"

  • 2

    Lucas, is this what you want? https://answall.com/questions/17030/maneira-cross-browser-copiar-texto-para-a-%C3%81rea-de-transfer%C3%Aancia-Clipboard

1 answer

1


It’s pretty simple, and it doesn’t necessarily need Jquery. There’s a native function that does this:

$('#ola').click(function(){
        //Visto que o 'copy' copia o texto que estiver selecionado, talvez você queira colocar seu valor em um txt escondido
    $('#seuTxt').select();
    try {
            var ok = document.execCommand('copy');
            if (ok) { alert('Texto copiado para a área de transferência'); }
        } catch (e) {
        alert(e)
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="seuTxt" value="Olá mundo!" />
<input type="button" id="ola" value="Clique em mim" />

After clicking the button, try to give CTRL+V somewhere, it will paste the text

  • Arthur, I liked it, it worked here, but I have a question now. Would you have the same, but without having to select? Or instead of copying the selected content, does it copy the value="" text? For example: <div value="ola mundo"></div> Document.execCommand('copy'). value;

  • 1

    No, because the document.execCommand('copy') selects the text that is selected on the screen, so I gave a select before using it :). You can do some maracutaias, like copy to a hidden place and select this hidden, but I see no reason

  • It’s just, for example, I have a banner that has discount coupon information. in case the text of the discount coupon is GANHE100, wanted that if this banner was clicked, it copied this text, then thought to put this text maybe in some image value, and when clicking on the banner he copy it. Or copy some random text that I define already inside Javascript.

  • 1

    But does this answer not work? $('#textDaImage'). select(); Document.execCommand('copy')

  • Now I saw the hidden text there that you put, I think I can put the text anywhere in HTML, and copy by clicking the banner, ne?

  • @Lucascarvalho yes

  • Thank you Artur! :)

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.