Difficulties with integrating tooltips into SVGs

Being a minimalist, I am facing restrictions while working on a website. I desire interactive tooltips to appear when users hover over specific sections of my SVG. However, I also want to incorporate this interactivity within the SVG itself. The challenge is that I have limited knowledge of Javascript. Initially, I attempted to achieve this using CSS only but discovered that embedding CSS inside the SVG restricts the full functionality of CSS, especially in creating dynamic tooltips.

Subsequently, I delved into Javascript, which can also be embedded in the SVG. I found the tooltips generated through Javascript more appealing than those created with the title tag. Nevertheless, there are lingering issues.

One problem is that the SVG file renders properly in Chrome but fails to display in Firefox. The reason behind this inconsistency remains elusive.

Another issue arises even in Chrome where I struggle with displaying multiline tooltips effectively due to limitations. Any advice or suggestions would be greatly appreciated!

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg id="oidc" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 422 339.2">
  <style type="text/css">
    .st13 {
        fill:#d9489b
    }
    .st13:hover {
        cursor:help;
        fill:#E66E31;
    }
    #tooltip {
          dominant-baseline: hanging;
          font-size: 8px;
      }
  </style>
  <switch>
    <g>
    <g>
      <circle class="st13" cx="47.8" cy="69.2" r="6" data-tooltip-text="I am some fairly long text." />
      <circle class="st13" cx="321.2" cy="65.7" r="6" data-tooltip-text="I am some much much much much much much longer text, so long that I cannot discuss or itemize my exact length....it's looooong, very long. I can't say more."/>
    </g>
    <g id="tooltip" visibility="hidden" transform="translate(87.9511512134412 127.90914747977598)">
      <rect x="2" y="2" width="52.90066909790039" height="24" fill="black" opacity="0.4" rx="2" ry="2"></rect>
      <rect width="52.90066909790039" height="24" fill="lightblue" rx="2" ry="2"></rect>
      <text x="4" y="6">A box</text>
    </g>
  </g>
    <script type="text/ecmascript">
  (function() {
      var svg = document.getElementById("oidc");
      var tooltip = svg.getElementById("tooltip");
      var tooltipText = tooltip.getElementsByTagName("text")[0];
      var tooltipRects = tooltip.getElementsByTagName("rect");
      var triggers = svg.getElementsByClassName("st13");

      for (var i = 0; i &lt; triggers.length; i++) {
        triggers[i].addEventListener("mousemove", showTooltip);
        triggers[i].addEventListener("mouseout", hideTooltip);
      }

      function showTooltip(evt) {
        var CTM = svg.getScreenCTM();
        var x = (evt.clientX - CTM.e + 6) / CTM.a;
        var y = (evt.clientY - CTM.f + 20) / CTM.d;
        tooltip.setAttributeNS(null, "transform", "translate(" + x + " " + y + ")");
        tooltip.setAttributeNS(null, "visibility", "visible");

        tooltipText.firstChild.data = evt.target.getAttributeNS(null, "data-tooltip-text");
        var length = tooltipText.getComputedTextLength();
        for (var i = 0; i &lt; tooltipRects.length; i++) {
          tooltipRects[i].setAttributeNS(null, "width", length + 8);
        }
      }

      function hideTooltip(evt) {
        tooltip.setAttributeNS(null, "visibility", "hidden");
      }
    })()
    </script>
  </switch>
</svg>

Answer №1

Try relocating the <script> element and its contents outside of the <switch> element for optimal functionality.

In fact, the <switch> element may not be necessary at all, so removing it completely could streamline your code.

While this specific issue is a known bug in Firefox, it's a rare occurrence that can be easily resolved. It's worth noting that most developers do not typically include scripts within switch elements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of NodeJS modules through exports referencing

Encountering difficulties referencing dynamic variables related to mongoose models based on user session location value. Two scripts are involved in this process. The first script is called location.js & reporting.js In the location.js script: module.ex ...

What attribute should I utilize to ensure the image always takes priority over text when using @media queries?

resolution My goal is to have the image appear on top of the text when resizing the window, but maintain the appearance shown in the attached image when using a larger resolution. Below is the CSS code I am currently using: .section4 { text-align: cen ...

Failure to trigger AJAX error function when database match is not located

UPDATED: Having some issues with my code entry box when a match is not found in the database. Below are the results for both a good and bad match. Check out my code snippet: function checkDiscountCode() { var discount; if ($('#dbReturnString') ...

"Dynamic navigation bar that remains in place even while scrolling past Adsense advertisements

Looking to implement a sticky menu for my blog using jQuery. The menu is functioning as desired, however, the issue arises when I scroll down on a page that contains adsense - the menu ends up going under the ad. What could be causing this problem? Below ...

The style of the button label does not persist when onChange occurs

Encountered an interesting issue here. There is a button designed for selection purposes, similar to a select item. Here's the code snippet: <button class="btn btn-primary dropdown-toggle" style="width: 166%;" type="button" id="dropdownMe ...

How does the Express next() function trigger the execution of the following middleware?

Can someone please explain how the next() function is able to call the subsequent middleware or route? I've searched everywhere but can't seem to find a good resource with the actual code. If anyone could share where I may find this information, ...

Exploring the integration of foreign languages within C# code?

In search of a C# expert who can assist me with a question I've been struggling to find an answer for all day. Google searches have yielded outdated information, and I need fresh insight. Wondering if there's a way to incorporate CSS and HTML in ...

Discovering the XPath of an element

Can anyone help me locate the XPath for the hamburger navigation icon on the website , specifically in the upper left corner? I am developing a Python script using selenium and need it to be able to click this particular button. Here's what I have tr ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...

Retrieving information using an ajax request in JavaScript

Although this question may have been asked several times before, I have yet to find a satisfactory answer. I passed a URL in an Ajax call and I am trying to retrieve data from the database through a query in the success method of the Ajax request, but for ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/pickers"; import DateFnsUtils fro ...

What is the purpose of including window and undefined as parameters in this jQuery plugin?

Exploring the jquery resize plugin has left me puzzled about its inner workings: Typically, we only pass a jQuery object into jquery plugins like this: (function($){ ....plugin code.... })(jQuery); However, in the "resize" plugin, both window and un ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

Altering the dimensions of Bootstrap's default navbar for a more compact look

Currently, I am attempting to modify the size of Twitter Bootstrap's standard navbar to a smaller dimension. My goal is to have the Brand/logo on the left side, menu options in the center, and social media icons on the right side within the navbar. U ...

How can you access the query in Next.js API when req.query is initially set to undefined?

Is there a way to compare the value of req.query with the cookies on the site, even when req.query is undefined upon initial load? How can this be addressed? export default async function handler(req, res) { const { method } = req; const userId = req ...

Steps to retrieve data (token) from developer tools and incorporate it into a fetch Post request

Is there a simple way to extract data using dev tools and insert it into a fetch request? I am trying to make a POST request through the console, but I am struggling to correctly copy a token. I attempted to use querySelector but instead of finding the t ...

Express Concurrency: Managing Multiple Tasks Simultaneously

Looking to create an API using Express that is capable of processing requests either through multithreading or multiprocessing. For example, the following API has a 5-second sleep before responding. If I make 3 quick calls to it, the first response will ta ...

Facing troubles with the file format while trying to upload a CSV file to dropbox.com

My goal is to develop a Chrome extension that allows users to upload files directly to Dropbox.com. While most aspects of the functionality are working smoothly, I am encountering some challenges with the CSV format. The code snippet below demonstrates how ...

Error encountered in thread "main": Issue with parsing string literal

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FindElementsUsingJS { static WebDriver driver= new FirefoxDriver(); public static void main(Stri ...

Encountering an internal/modules/cjs/loader.js:892 error when attempting to install the newest version of node.js on Windows 10

After recently updating my node.js to the latest version using chocolatey, I encountered a problem with my command prompt displaying the following error: internal/modules/cjs/loader.js:892 throw err; ^ Error: Cannot find module 'C:\Users&bso ...