I make a simple coupon clipper with ClipboardJS. My purpose is that when the user clicks on the Coupon button to clip it (copy). The Coupon will display the string Copied, then return to show the original Coupon after a moment.
Unfortunately, if there are two or more coupons on the same page, the returned value will always be the first Coupon. I tried to play around with jQuery closest, but I couldn't figure it out.
Here is my code:
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"></script>
<p>
Clip Coupon <button class="coupon_clipper" data-clipboard-text="10PERCENT">10PERCENT</button> to receive 10% discount for order over 100$
</p>
<p>
Clip Coupon <button class="coupon_clipper" data-clipboard-text="1PERCENT">1PERCENT</button> to receive 1% discount for order over 100$
</p>
<style>
.coupon_clipper {
border-style: dashed;
}
</style>
Javascript
<script>var cClip = new ClipboardJS('.coupon_clipper');
cClip.on('success', function(e) {
$(e.trigger).text('Clipped');
e.clearSelection();
setTimeout(function() {
$(e.trigger).text($('.coupon_clipper').closest('.coupon_clipper').attr('data-clipboard-text'));
}, 250);
});
</script>
e.trigger
return the element you clicked. So you can use that to get theattribute
as well as to set text.Notice
$('.coupon_clipper').closest('.coupon_clipper')
this will return always first, you have to think with respective to action you performed on which element. and in your case it will be the same so you can you directlye.trigger
which returns the button you clicked.