I'm trying to code a chrome extension which highlights certain names and gives you additional information about the name inside a tooltip. Basically, I have an object with names and IDs like this:
var list = {
'Name1' : 'ID0001',
'Name2' : 'ID0002',
}
Then I'm using a jQuery highlight plugin to highlight every occurance of the keys in the document and assigning a span element with a class corresponding to the value of the key (for Example ID0001), which works fine...
$.each(list, function(key, value) {
$("p").highlight(key, {caseSensitive: false, className: value });
});
and results in this:
<span class="ID0001">Name_1</span>
Next, I'm trying to select every element with a class name containing the first part of the ID and activate Tooltipster:
$('span[class*=ID]').tooltipster({
interactive: true,
content: $(<p>Loading...</p>),
contentAsHTML: true,
functionBefore: function(origin, continueTooltip) {
continueTooltip();
// Below, I'm trying to get whole ID, without the
// 'tooltipstered' class, that Tooltipster assigned.
var id = $(this).attr('class').replace(' tooltipstered','');
$.getJSON(chrome.extension.getURL('db.json'), function(db) {
// Inside here, I'm using the ID to get information from a json
// file and store it in a variable called 'content', e.g.
var content = '<p>db[id].link</p>';
// Then I'm trying to update the content of the tooltip:
origin.tooltipster({
content: content,
contentAsHTML: true
});
}
});
All of this code is inside this:
$(document).ready(function() { });
Now, if I hover over a span with a name inside for the first time, tooltipster won't do anything, and the Chrome console will say this:
Uncaught ReferenceError: content is not defined
But I hover over it a second time it will show me the correct content. Additionally, If I hover over a name for the first time and another name the second time, the tooltip will show the content for the first name.
I'm fairly new to JS and jQuery and I just can't find out what I'm doing wrong here.
I've found a few other threads about similar issues, bt none of the proposed solutions worked for me.
Here is the "complete" updated code:
$(document).ready(function() {
$.each(list, function(key, value) {
$("p").highlight(key, {caseSensitive: false, className: value });
});
$('span[class*=ID]').tooltipster({
interactive: true,
contentAsHTML: true,
content: 'Loading...',
functionBefore: function(origin, continueTooltip) {
continueTooltip();
var id = $(this).attr('class').replace(' tooltipstered','');
var content = generate_content(id);
origin.tooltipster('content', content);
}
});
function generate_content(id) {
$.getJSON(chrome.extension.getURL('db.json'), function(db) {
// Getting information from the .sjon and storing it in "content"
});
return content;
}
});