Can't get id of hovered svg element using jquery

Viewed 280

I want to get the id of the svg-element (text) which has been hovered. The HTML:

<svg class="compass-svg" width="200" height="200">
     <text id="textN" x="93" y="55" fill="#000">N</text>
     <text id="textE" x="145" y="105" fill="#000">O</text>
     <text id="textS" x="95" y="158" fill="#000">S</text>
     <text id="textW" x="40" y="105" fill="#000">W</text>
</svg>

This is the javascript code:

$('text').hover(() => {
    //this is not working
    console.log($(this).attr('id'));

    //this is also not working
    console.log(this.attr('id'));

    //I've also tried this
    console.log(this.id);
});

When I hover for example the first text element it should write 'textN' to the console.

3 Answers

Use event.target.id, here is an example:

$('text').hover((e) => {
  //this is working
  console.log(e.target.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg class="compass-svg" width="200" height="200">
     <text id="textN" x="93" y="55" fill="#000">N</text>
     <text id="textE" x="145" y="105" fill="#000">O</text>
     <text id="textS" x="95" y="158" fill="#000">S</text>
     <text id="textW" x="40" y="105" fill="#000">W</text>
</svg>

You are using an arrow function that changes scope inside it. If you use function keyword, you can get the values normally:

$('text').hover(function() {
    // This will work
    console.log($(this).attr('id'));

    // This will also work
    console.log(this.id);
});
.as-console-wrapper {
  max-height: 85px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg class="compass-svg" width="200" height="200">
     <text id="textN" x="93" y="55" fill="#000">N</text>
     <text id="textE" x="145" y="105" fill="#000">O</text>
     <text id="textS" x="95" y="158" fill="#000">S</text>
     <text id="textW" x="40" y="105" fill="#000">W</text>
</svg>

you can use this snippet with hover over and over out hope that help you

$('text').hover(function () {
    // hover over
    console.log($(this).attr('id'));

  }, function () {
    // hover out
    console.log($(this).attr('id'));
  }
);
Related