javascripthtmlcssmaterial-design-lite

MDL Add tooltip with JS


I'm making a chatting web app, and in it there are emojis.

I'm using MDL to make this, and for the emojis, I'm using tooltips. See this picture of expected behavior:

Emoji with Joy

So anyway, to put these emojis here is the code I have

messageElement.innerHTML = messageElement.innerHTML.replace(/:alien:/g, '<div  id=":alien:"><img class="emoji" src="https://greenbayrules.github.io/host/emojis/faceemoji/alien.png" /> </div><div class="mdl-tooltip" data-mdl-for=":alien:">:alien:</div>');

This code runs whenever a new message is received in the database.

The problem is this these emojis tooltips don't work. The elements appear in the inspect element, but they don't show up on hover. On the other hand, if I copy paste that same HTML element and put it in the HTML of the code, it works fine.

This leads me to think that the MDL does some sort of script when the website is loaded, that activates all the tool-tips.

First of all, what is the problem here? If the problem is that this script is running before my script that adds the emojis does, then how do I re-run that script so my emojis will load with the tool-tip working?


Solution

  • Have you tried using componentHanlder.upgradeElement? For example:

    messageElement.innerHTML = messageElement.innerHTML.replace(/:alien:/g, '<div  id=":alien:"><img class="emoji" src="https://greenbayrules.github.io/host/emojis/faceemoji/alien.png" /> </div>');
    
    var tooltip = document.createElement('div');
    tooltip.className = 'mdl-tooltip';
    tooltip.setAttribute('data-mdl-for', ':alien:');
    tooltip.innerHTML = ':alien:'
    componentHandler.upgradeElement(tooltip);
    messageElement.appendChild(tooltip);