Tippyjs: How can I add an event listener to a link in the tippy.js dropdown?

Created on 10 Jan 2020  路  5Comments  路  Source: atomiks/tippyjs

How can I add an event listener to a link in the tippy.js dropdown?

Here is a Codepen

    const Dropdowns = tippy(
        document.querySelectorAll('[data-trigger="dropdown"]'),
        {
            theme: "blank",
            maxWidth: 260,
            interactive: true,
            arrow: true,
            animateFill: false,
            trigger: "click",
            placement: "bottom",
            content(reference) {
                const id = reference.getAttribute("data-template");
                let template = document.getElementById(id);

                if (template === null) {
                    template = reference.nextElementSibling;
                }
                return template.innerHTML;
            }
        }
    );

I would like to add an event listener to the link. It doesn't work ...

btnFilter.addEventListener(
    "click",
    function(ev) {
        console.log("btnFilter was clicked! ");
        // filter stuff goes here
    },
    false
);

I think it doesn't work because tippy.js copies the HTML from the dropdown?
Is it possible that tippy does not copy the HTML and uses the "original" html?

Most helpful comment

https://codepen.io/atomiks/pen/bGNMGKG

  1. You need to select the btn element before tippy moves it out of the document, otherwise you can't add the event listener since it won't be found when you query select it.
  2. You have hidden attribute on the template, so you need to remove that attribute when passing the element directly. The .innerHTML worked in this case since it was passing the inner contents of the template.

All 5 comments

You just need to remove the .innerHTML at return template.innerHTML. You're passing the string not the element itself

You just need to remove the .innerHTML at return template.innerHTML. You're passing the string not the element itself

Unfortunately that does not work. I posted a codepen. I hope this helps to identify the problem.

Here is a Codepen

https://codepen.io/atomiks/pen/bGNMGKG

  1. You need to select the btn element before tippy moves it out of the document, otherwise you can't add the event listener since it won't be found when you query select it.
  2. You have hidden attribute on the template, so you need to remove that attribute when passing the element directly. The .innerHTML worked in this case since it was passing the inner contents of the template.

Also how are you using 3.4.1? That's 2 majors old 馃槥

No. I use "tippy.js": "^ 5.1.2"

Thank you! That works now. ;-)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

divmgl picture divmgl  路  3Comments

madjennsy picture madjennsy  路  4Comments

andrewckor picture andrewckor  路  4Comments

skazhikadyadya picture skazhikadyadya  路  3Comments

Christian24 picture Christian24  路  3Comments