Search code examples
jquerytooltipclipboardzeroclipboard

Boostrap 3 clipboard and tooltip with dynamic ID


I have the following code, but I need all the ID with #coupon to work with dynamic post ID, for example: #coupon-3567

jQuery('#coupon').tooltip({
  trigger: 'dblclick',
  placement: 'top'
});

function setTooltip(message) {
    jQuery('#coupon').tooltip('enable');
  jQuery('#coupon').attr('data-original-title', message).tooltip('show');
}

function hideTooltip() {
  setTimeout(function() {
    jQuery('#coupon').tooltip('hide');
    jQuery('#coupon').tooltip('disable');
  }, 2000);
}

var clipboard = new Clipboard('#coupon');
 
clipboard.on('success', function(e) {
  setTooltip('¡Copied!');
  hideTooltip();
});

clipboard.on('error', function(e) {
  setTooltip('Error');
  hideTooltip();
});

I have modified the html code to get the ID, but I don't know how to make the ID work in the JS, I have tried for many hours and I have not succeeded.

<div id="coupon-<?php echo get_the_ID() ?>" class="cnt-cpn-bd" data-post-id="<?php echo get_the_ID() ?>" data-clipboard-text="<?php the_field( 'coupon_code', get_the_ID() ); ?>">

Can anybody help me please?


Solution

  • For example

    <div id="coupon-444"></div>
    

    You will get the Id with

    console.log($('[id^=coupon]').attr('id'));
    result: coupon-444 
    

    Then use

    var id = $('[id^=coupon]').attr('id');
    $('#' + id).tooltip({
      trigger: 'dblclick',
      placement: 'top'
    });
    
    function setTooltip(message) {
      var id = $('[id^=coupon]').attr('id');
      $('#' + id).tooltip('enable');
      $('#' + id).attr('data-original-title', message).tooltip('show');
    }
    

    For hide

    function hideTooltip() {
      var id = $('[id^=coupon]').attr('id');
      setTimeout(function() {
         $('#' + id).tooltip('hide');
         $('#' + id).tooltip('disable');
      }, 2000);
    }