Home > Back-end >  How to have a unique hover description for every element in an array?
How to have a unique hover description for every element in an array?

Time:09-20

Not sure if my title accurately describes my dilemma but basically, I have a list of names and I want each of them to have a unique description when hovered over with a mouse.

That sounds easy enough, right?

But the problem is, the names are elements in an array.

I can't exactly do < a title="DESCRIPTION" /> ARRAY CODE < /a> because each name inside that array will have the same hover description.

How would I code it so that each name in my array will have a different hover description?

CodePudding user response:

You can use an object to map descriptions to names. Like this:

const names = {
    'Bob': 'me',
    'Joe': 'my friend',
    'Bill': 'a random guy',
}

Then you can loop over the object with a for in creating elements. Like this:

for (const name in names) {
    $('body').append(`<a title="${names[name]}"> ${name} </a>`);
}

Because objects have a time complexity of O(1), this should be faster than using a multidimensional array. However, JS objects are not ordered. If you need the names to be in order, consider using a map. Like this:

const names = new Map();
names.set('Bob', 'me');
names.set('Joe', 'my friend');
names.set('Bill', 'a random guy');

for (const name of names) {
    $('body').append(`<a title="${name[1]}"> ${name[0]} </a>`);
}

CodePudding user response:

Declare your titles in an array with the same order as the array of the anchor links, then set each title to the opposite anchor link.

const titles = ['a', 'b', 'c'];
const anchors = document.querySelectorAll('a');
for (const a in anchors) {
for (const t in titles) a.SetAttribute('title', t);}
  • Related