How to take the "src" value of an "img" tag through Javascript and copy it to clipboard?

Asked

Viewed 8,644 times

4

Guys I want to make sure that when clicking on an image, your url is copied to the clipboard, I tried to use Clipboard but I was only able to make a copy of the text.

var a = document.getElementById('id' + img).src.toString();
alert(a);

want to do this but without the user having to press Ctrl c, I want the value to be copied when the user click on the img that calls this function.

Function getsrc(img) { var a = Document.getElementById('id' + img).src.toString(); window.prompt("Copy to clipboard: Ctrl+C and type Enter", a); }

Value shown in Alert : http://localhost:8084/application/2/img.jpg . This value should go to the transfer area,at Ctrl+v should be pasted.

With this code appears the path I want you to go to the clipboard, but I cannot copy it to the clipboard automatically when a img is clicked.

  • your link will not work ederjc as it is on the localhost

  • is just an example can be any url, and it works yes, when manually copying an img of src it appears normally.

  • Rsrs, when I said it won’t work, that’s when someone clicks there. This what you want to do I was seeing one of these days, if I find the reference, put here for you

  • What do you want here : http://answall.com/questions/89139/como_copiar-para-%C3%A1rea-de-transfer%C3%Aancia-em-javascript, Additional Reading

  • I understood thank you :D

4 answers

3

You can use the library clipboard.js, click here to see your documentation.

Solution using clipboard.js:

// Inicia o Clipboard no elemento "button"
var copiar = new Clipboard('button', {

    // Define o texto a ser copiado
    text: function(trigger) {

        // Obtem "src" da "img" que está no mesmo nível do "button"        
        return $(trigger).siblings('img').attr('src');
    }


});

// Retorna um alert se copiar com sucesso.
copiar.on('success', function(e) {
   alert('Copiado para a area de transferencia!');
});

// Retorna um alert se copiar com erro.
copiar.on('error', function(e) {
   alert('Houve um erro ou navegador não suportado');
});
<!-- CSS do Bootstrap, para ficar mais bonitinho :P -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!-- JS do Jquery e do Clipboard.js (NECESSÁRIO!) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>

<!-- Código com suas imagens! -->
<div class="col-xs-10 col-offset-2">
<div class="col-xs-5">
  <img src="https://pixabay.com/static/uploads/photo/2015/08/20/14/00/frog-897419_960_720.jpg" class="img-thumbnail" alt="Cinque Terre" width="100%">
  <button class="btn btn-block btn-primary">
   COPIAR
  </button>
</div>
<div class="col-xs-5">
  <img src="https://pixabay.com/static/uploads/photo/2015/08/20/14/00/frog-897418_960_720.jpg" class="img-thumbnail" alt="Cinque Terre" width="100%">
  <button class="btn btn-block btn-primary">
   COPIAR
  </button>
</div>
</div>

Other methods of use:

You can use the clipboard.js in various other ways, not limited to the demonstration posted, to complement I will be posting some examples, which are also contained on the documentation website

Copy value of input:

// Inicia o Clipboard no "button"
new Clipboard('button');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="col-xs-10">
  <div class="col-xs-8">
      <!-- Alvo a ser copiado -->
      <input id="id" class="form-control" value="Digite algo, ou clique em Copiar para copiar isso!">
  </div>
  
   <div class="col-xs-2">
      <!-- Botão para copiar -->
      <button class="btn  btn-block" data-clipboard-target="#id">
           Copiar
      </button>
  </div>
</div>

In that case the data-clipboard-target="" is responsible for copying the value of another element, in this case the input. So by clicking the user will copy the content written in the element defined in data-clipboard-target.

Copy pre-defined text into element:

// Inicia o Clipboard no "button"
new Clipboard('button');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="col-xs-10">
  <button class="btn btn-block" data-clipboard-text="Você copiou esse texto :O">
      Copiar!
  </button>
</div>

In that case the data-clipboard-text="" is responsible for defining the text to be copied. So clicking the user will copy the content written in the element data-clipboard-text.

Compatibility:

Official library support list:

Chrome 42+
Mozilla 41+
Internet Explorer 9+
Opera 29+

Furlough:

Imagery are under "Public Domain":

https://pixabay.com/pt/sapo-adeus-viagens-bagagem-holdall-897420/
https://pixabay.com/pt/sapo-adeus-viagens-bagagem-holdall-897418/

Clipboard.js is under "MIT License":

https://zenorocha.mit-license.org/

2

Below an example made with pure Javascript.

var reply_click = function()
{
    alert("Copiado para a área de transferência");
  
  //Criando um "hidden" input
  var aux = document.createElement("input");
  
  // Atribuir-lhe o valor do elemento especificado
  aux.setAttribute("value", this.src);

  // Anexá-lo ao corpo
  document.body.appendChild(aux);

  // Highlight conteúdo
  aux.select();

  // Copiando o highlighted text
  document.execCommand("copy");

  // Removendo do corpo
  document.body.removeChild(aux);
}
//imagem 1
document.getElementById('1').onclick = reply_click;
//imagem 2
document.getElementById('2').onclick = reply_click;


  
<img id="1" width="100" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/careers/careers-logo.png?v=c252e7f960b1"/>
<br /><br />
<img id="2" width="100" src="https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png"/>
<br/><br/><input type="text" placeholder="Cole aqui após clicar na imagem acima" />

0

In this link There’s an example I used and it worked. Note: Using only Jquery.

var src = $('img[alt="example"]').attr('src');
alert("caminho da imagem = " + src);

-1

Using jquery should work like this:

var imagem = $("#id-da-imagem").attr('src');
alert(imagem);
  • From jQuery 1.6 the function attr was replaced by prop - http://api.jquery.com/prop/

  • 2

    Ricardo, he’s trying to copy to the clipboard, so you just took the src attribute

  • ah, I get it now

  • Pedro Camara, I have seen cases where attr() is still used, but in fact, prop() has come to stay

  • 2

    @Pedrocamarajunior was not replaced, they simply put together a new method for DOM properties and the .attr is specified for HTML attributes.

Browser other questions tagged

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