1

I am trying to develop an interactive SVG map and I want to do stuff when the mouse enters rectangles within the SVG image. Currently, the code logs to the console when my mouse enters the SVG image, but not when I mouse over the rectangles. Any help would be much appreciated. Thanks!

<object onload="svgOnLoad()" id="activeSVG" data="SVGNAME.svg" type="image/svg+xml">
</object>

  <script>
            function svgOnLoad() {
              console.log("SVG Loaded");
              $("#activeSVG").mouseenter(function(e) {
                console.log("In the SVG")
              });

              //Executed when the mouse enters an SVG rect element
              $("rect").mouseenter(function(e) {
                console.log("Mouse Entered rectangles!!")
              });
            }
  </script>
Joe Kollin
  • 13
  • 4

2 Answers2

0

There is a short description, e.g., on https://www.tutorialspoint.com/svg/svg_interactivity.htm.

For mouseover events you need the jQuery mouseover function: https://api.jquery.com/mouseover/

Guybrush
  • 710
  • 7
  • 12
  • Right, I'm aware that I need to change the event eventually, but it is not logging either way. It should still log when I enter the rectangle and it currently is not. – Joe Kollin Jun 05 '17 at 17:59
  • Try to put the code in the `document.ready()` function. Maybe, the registration of the events is done before the SVG is completely loaded. – Guybrush Jun 05 '17 at 18:13
  • But its being called onload which occurs after ready, so I don't believe thats the issue – Joe Kollin Jun 05 '17 at 18:17
  • Are the rectangles in the front? Are there others elements overlapping the rectangles? – Guybrush Jun 05 '17 at 18:22
  • Yes, the rectangles are in the front, but they are logically segmented in groups `` – Joe Kollin Jun 05 '17 at 18:24
  • Are the rectangles filled? If not, then you have to add the CSS property `pointer-events: all`. Cf. https://stackoverflow.com/questions/9208244/how-to-hover-over-an-svg-rect – Guybrush Jun 05 '17 at 18:28
0

After messing around with it for a bit I found what needed to be added. You need to get the content of the svg object and then play with it from there. I've included the new script code below.

<script>
            function svgOnLoad() {
              // Get SVG object
              var officeMapFloor = document.getElementById("activeSVG");

              // Get the content of the SVG object
              var svgDoc = officeMapFloor.contentDocument;

              // Access an ID within the content of the object
              var rect = svgDoc.getElementById("siesta");

              // Apply the event listener
              rect.onmouseover = function(){
                console.log("Finally in the rectangle");
              };

            }
 </script>
Joe Kollin
  • 13
  • 4