Search code examples
jquerytippyjs

Bind events to elements inside TippyJS HTML tooltip


I'm using TippyJS to show HTML tooltips. I have some interactive content inside the tooltip so I'd like to bind events to those elements. Because the tooltip content is generated dynamically by Tippy, standard jQuery event bindings don't seem to work.

I've set up an example like this:

HTML:

<button id="t1" class="btn tippy" >hover here</button>

<div id="tip-content" style="display: none;">
    Trigger event when clicking this 
    <button class="btn btn-click">button</button>
</div>

JS:

new Tippy('#t1',{
  position:'top',
  interactive:'true',
  html: '#tip-content'
});

$('.btn-click').click(function(){
  console.log('clicked!');
});

There's a working CodePen here.

I want to do a console.log when the button in the tooltip content is clicked, but can't get it to work. I've tried binding the button click event inside a Tippy 'show' event, like this, but again it doesn't work:

onShow(instance) {
    $('.btn-click').click(function(){
      console.log('clicked!');
    });
  }

Can anyone advise how to get this event binding to work?

Many thanks.


Solution

  • TippyJS has an onShown event which fires when the tooltip is fully shown, this is not the same as the onShow event you are using, which fires at the start of the tooltip animation.

    Secondly, in your Codepen you are using version 0.3.0 of TippyJS, in my Codepen I am using the latest version 2.5.4. I can't say for sure that the onShown event existed in the library 2 major versions back.

    Working Codepen