sojutyp
sojutyp

Reputation: 316

Many <img> Ids using the same routine

I have this code that copies the value of an <img> to the clicker's clipboard and provides a notification that the value has been copied. In the final version, many <img> with their own value (id="me_too",id="me_too",id="me_too",...) should be copied to the clipboard and basically go through the same routine. I guess this is possible using arrays or loops? I'm quite new to jQuery and programming, so help would be very much appreciated!

HTML:

<p><img id="smiley" value=":)" src="..." />
<p><img id="me_too" value=";)" src="..." />
<p><img id="and_me" value=":D" src="..." />
<p><img id="and_me_too" value=":X" src="..." />

<p id="info_satz">&nbsp;</p>

jQuery:

        jQuery('#smiley').on('click', function() {
            var value = jQuery(this).attr('value');

            copyToClipboard(value);
            jQuery('#info_satz').hide().html(value + '  copied to clipboard.').fadeIn('normal');
        });

        function copyToClipboard(value) {
            var $tmpInput = $('<input>');
            $tmpInput.val(value);
            jQuery('body').append($tmpInput);
            $tmpInput.select();
            document.execCommand('copy');
            $tmpInput.remove();
        }

Upvotes: 0

Views: 27

Answers (1)

DBS
DBS

Reputation: 9984

Just use a class rather than ID's.

Give each image a class, e.g. yourClass

<img id="smiley" class="yourClass" value=":)" src="..." />

Than select all the image elements using that class, and add the event listener:

jQuery('.yourClass').on('click', function(){ ... }

Your code is already relative to the element that clicked it (since you use this to select the value) so the rest should work as expected.

Full example of your modified code:

jQuery('.yourClass').on('click', function() {
  var value = jQuery(this).attr('value');

  copyToClipboard(value);
  jQuery('#info_satz').hide().html(value + '  copied to clipboard.').fadeIn('normal');
});

function copyToClipboard(value) {
  var $tmpInput = $('<input>');
  $tmpInput.val(value);
  jQuery('body').append($tmpInput);
  $tmpInput.select();
  document.execCommand('copy');
  $tmpInput.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <img id="smiley" class="yourClass" value=":)" src="..." />
</p>
<p>
  <img id="me_too" class="yourClass" value=";)" src="..." />
</p>
<p>
  <img id="and_me" class="yourClass" value=":D" src="..." />
</p>
<p>
  <img id="and_me_too" class="yourClass" value=":X" src="..." />
</p>

<p id="info_satz">&nbsp;</p>

Upvotes: 1

Related Questions