Getting title of SVG path

Okay, I have an SVG with several paths. I want to get the title of a path when a user hovers over it. I thought it seemed simple but I have got my proverbials in a twist.

This is what I have tried:

const p = document.querySelectorAll("path");
p.forEach (function(item) {
  item.addEventListener("hover", function () {
    const t = p.getAttribute("title");
    console.log(t);
  });
});

There are no console errors, but my log(t) doesn’t execute either.

There’s no hover with events - use mouseover. Then you have a scope issue and need to get the item.attribute, not p.

const p = document.querySelectorAll("path");
p.forEach (function(item) {
  item.addEventListener("mouseover", function () {
    const t = item.getAttribute("title");
    console.log(t);
  });
})
2 Likes

Brill. Thanks, guv!

1 Like

And the next issue. I now have the following:

document.querySelectorAll("path").forEach (function(item) {
  item.addEventListener("mouseover", function () {
    document.querySelector("#region").innerHTML = item.getAttribute("title");
    item.style.fill = "#f00000";
  });
})

Trouble is each are remains highlighted in red. What I want is when a new path is moused-over for the old one to go back to a white fill.

Is it best/easiest just to set them all to white?

Set the color via css:hover instead of in the js?

2 Likes

Yes, that’s what I originally did, but then it disappears whereas the name as in the innerHTML remains. I think I’d like both to remain till another path is hovered over.

I decided that click was more appropriate than mouseover, so this is what I ended up with:

p = document.querySelectorAll("path");

function clearAll () {
  for (let pi of p) {
    pi.style.fill = "#f9f9f9";
  }
}

p.forEach (function(item) {
  item.addEventListener("click", function () {
    clearAll();
    document.querySelector("#region").innerHTML = item.getAttribute("title");
    item.style.fill = "#f00000";
  });
})

Not sure if there’s a better way to do it, but it works.

I would have used a css class for the toggle.

Something like this (But I;m sure the js could be tidied up :slight_smile: ).

const path = document.querySelectorAll("path");
var oldindex = 0;
path.forEach (function(item, index) {
  item.addEventListener("mouseover", function () {
    document.querySelector("#region").innerHTML = item.getAttribute("title");
    path[oldindex].classList.remove('fillme');
    item.classList.add('fillme');
    oldindex =index;
  });
})
.fillme{
  fill:red;
}
3 Likes

That’s better than wot I got, guv. Thanks!

1 Like