D.S D.S - 9 months ago 118
HTML Question

Materialize tooltip only works outside function

I am having issues manipulating this html element:

<a id="q" class="btn tooltipped" data-position="bottom" data-delay="50" data-tooltip="I am a tooltip">Hover me!</a>


using this JavaScript code:

$('#q').attr('data-tooltip', 'new data');


Please look at the following scenarios:

Scenario 1

< script >

function A() {
// Do function A stuff
}

function B() {
// Do function B stuff
$('#q').attr('data-position', 'right'); // THIS WORKS
$('#q').attr('data-tooltip', 'new data'); // THIS DOESN'T WORK
}

function C() {

// Do function C stuff
} < /script>


Scenario 2

< script >
$('#q').attr('data-tooltip', 'new data'); // THIS WORKS

function A() {
// Do function A stuff
}

function B() {
// Do function B stuff
$('#q').attr('data-position', 'right'); // THIS WORKS

}

function C() {

// Do function C stuff
} < /script>


Why is it that the code $('#q').attr('data-tooltip', 'new data'); only works outside a function? My goal is to get the code to work within function B. Why is it that one code works but the other doesn't? As seen in scenario. 1. I want to dynamically change the text within the tooltip when function B runs.

Answer Source

I think what's happening is that your code outside of your function call runs immediately. So it runs on your tooltips changing the data attribute BEFORE materialize even has a chance to set it as a tooltip.

You will need to change the content like you are doing, then re-initialize tooltip() to get the updates.

For explanation of Scenario 1: Your data-position code works in that situation because materialize handles that attribute differently than actual content inside of the tooltip.

From what I recall, materialize actually sets the content, and it doesn't allow for changing of the content without re-initialization of the tooltip.

The position of the tooltip is initialized at the event of mouseover so your code would update the position just fine and then materialize would recognize this update on the mouseover event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download