n000000b
n000000b

Reputation: 31

Multiple tippy.js tooltips with html content

I am trying to get multiple tooltips on the same page with different HTML content using tippy.js. This content varies - it might me just image or text formatted with HTML tags or text + image(s). How can I make this work?

I tried to run this code but didn't had much success

 <a class="btn" href="#">Text</a>
<div class="myTemplate">
  <b>Text</b> <img src="https://i.imgur.com/dLcYjue.png">
</div>
 <a class="btn" href="#">Text2</a>
    <div class="myTemplate">
      <b>Text2</b>
    </div>


<script type="text/javascript">
    tippy('.btn', {
  content: document.querySelector('.myTemplate')
})
    const clone = document.querySelector('.myTemplate').cloneNode(true)
</script>

Upvotes: 3

Views: 6003

Answers (2)

user1895720
user1895720

Reputation: 81

maybe this helps someone getting here again:

also check the documentation: https://atomiks.github.io/tippyjs/v6/html-content/

document.querySelectorAll('button[data-template]').forEach(btn => {
    tippy(btn, {
        content(reference) {
            const id = reference.getAttribute('data-template');
            const template = document.getElementById(id);
            return template.innerHTML;
        },
        allowHTML: true
    })
})
<script src="https://unpkg.com/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/tippy-bundle.umd.min.js"></script>

<button data-template="one">One</button>
<button data-template="two">Two</button>
<button data-template="three">Three</button>

<div style="display: none;">
  <div id="one">
    <strong>Content for `one`</strong>
  </div>
  <div id="two">
    <strong>Content for `two`</strong>
  </div>
  <div id="three">
    <strong>Content for `three`</strong>
  </div>
</div>

Upvotes: 5

theAnubhav
theAnubhav

Reputation: 533

tippy takes selector as its primary argument, You would need different ids to do this. If there are more than a couple of content tooltips/generated at runtime, I would recommend to use a common convention in setting id and using a for loop for iterating over it.

Considering, there are 2 content tooltips,

<a class="btn1" href="#">Text</a>
<div class="myTemplate1">
    <b>Text</b> <img src="https://i.imgur.com/dLcYjue.png">
</div>
<a class="btn2" href="#">Text2</a>
<div class="myTemplate2">
    <b>Text2</b>
</div>


<script type="text/javascript">
    tippy('.btn1', {
        content: document.querySelector('.myTemplate1')
    })
    tippy('.btn2', {
        content: document.querySelector('.myTemplate2')
    })
</script>

Upvotes: 0

Related Questions