Tips for displaying <p> element upon hovering over a specific area of an SVG image

I created a map and converted it to SVG. I want to display the name of each neighborhood when a user hovers the mouse over it.

I'm not sure how to achieve this or how to isolate the specific area of a neighborhood to make changes.

Here's a screenshot of that section of the website:

.

Users have been asking for more information for a complete answer. Here's the HTML code I used:

<div class="col-lg-6 col-md-6 col-sm-12 content-area">
    <object style="width: 500px; margin-top: 30px; margin-bottom: 30px;" type="image/svg+xml" data="<?php bloginfo('template_directory');?>/img/mapa-goiania-traco.svg"></object>
</div>

And here's the SVG code:

My main challenge right now is figuring out how to separate the specific areas of the neighborhoods within the SVG file in order to apply CSS changes. When I view the SVG file, it all looks like a jumble of numbers without any distinction between different neighborhood areas. I need to be able to select them individually to work with CSS effectively.

Answer №1

Check out this simple demo to experiment with. Rene suggested that applying classes (like paris in my example) to the SVG elements would be more precise. However, the way you structure your SVG code will determine if this is feasible. If not, consider using relative positioning for the SVG itself and position each section absolutely to have better control over the layout.

.container {
    display:flex;align-items:center;justify-content:center;
}

.map {
  background:lightgray;
  width:500px;height:500px;margin-top:250px;
}

.square {
  width:250px;height:250px;cursor:pointer;
}

.paris {
  background:blue;
}

.paris span {
  width:50%;margin-left:25%;
margin-top:25%;visibility:hidden;color:#FFF;}

.paris:hover span {
  visibility:visible;
}
<div class="container">
  <div class="map">
    <div class="square paris">
      <span>Paris (France)</span>
    </div>
    <div class="square montreal"></div>
    <div class="square boston"></div>
    <div class="square istanbul"></div>
  </div>
 </div>

Answer №2

Adding to my earlier comment, I decided to use File:Brazil State RiodeJaneiro.svg from WikiMedia (original owner holds all rights!) and made some tweaks to simplify it (removed most paths) for the snippet below.

I included

<text class="capital">
below the
<path class="capital">
of the State of Rio de Janeiro and set the text to be hidden by default. On :hover over the State of Rio de Janeiro (in dark red), I reveal the text using the adjacent selector (+) as mentioned in w3schools: CSS Selector Reference.

All the CSS code resides within the SVG file, ensuring that it not only functions when the SVG is embedded in your HTML, but also when the SVG file is opened in a browser.

You can find and run the SVG on Codepen (as the file is too large for SO), and below is the relevant code as I mentioned previously.

In a different answer on Stackoverflow, I implemented a similar approach to display text (responsively) when hovering over the top floor of an image of a building: SO62099505

CSS within SVG

<style>
    .capital {
        visibility: hidden;   /* text hidden by default */
        pointer-events: none; /* ignores cursor over text to prevent hover 'jitter' */

        /* Added for demo */
        font-weight: bold;
        font-size: 2800px;
        letter-spacing: 100px;

        fill: White;
        fill-opacity: 1;
        stroke: black;
        stroke-width: 75;
    }
    .estado { 
        fill: FireBrick; 
        cursor: pointer; 
    }

    /* Reveals text element adjacent to (below) path element when hovered over */
    .estado:hover + .capital { 
        visibility: visible; 
    } 
</style>

SVG Code


    <g id="Estados">
        <!-- State of Rio de Janeiro -->
        <path class="estado" d="M143583 140702l32 -32 0 -32 0 -32 65 -32 ... "/>
        <text class="capital" y="137500" x="146500">Rio de Janeiro</text>
    </g>

Answer №3

Appreciate the assistance from everyone!

Here's how I tackled the issue: I created the map using Inkscape and organized the neighborhoods into different layers. This allowed me to save the map as an SVG file with all the paths separated, making it simple to customize and modify as needed.

For those facing similar challenges, I highly recommend using Inkscape for editing and customizing SVG files. It provides nearly complete code that is easy to work with and customize to your liking.

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

Having difficulty interpreting the json data retrieved from the specified url

<html> <body> <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script> <script> $(document).ready(function () { $.ajax({ type: 'GET& ...

Struggling to fetch data from the Strapi page is posing a challenge

Currently, I am facing an issue where the frontend developers on my team are unable to retrieve data from the backend that I built for them using Strapi. Even after pulling my changes from github, they continue to face difficulties accessing the data. The ...

What factors influence Redux in determining when to update the user interface?

As per the design, when the state updates, the UI should also update accordingly. However, if I return a completely new object, it seems to have no effect on the UI. case 'clearArticleForm': let newState1 = {}; return newState1; } E ...

Routing in Next.js to create custom URL slugs for usernames, like (site.com/username), is a

I have a requirement to create username pages on my website, where each username will have its own page like site.com/jack The current folder structure I am using is pages > [user] > index.js, but this setup causes issues when someone tries to acces ...

jQuery was denied permission to implement inline styling due to non-compliance with the specified Content Security Policy directive

Currently, I am exploring the GitHub project play-silhouette-slick-seed, which serves as an illustration of the Silhouette authentication library for Play Framework in Scala. My goal is to incorporate it into my own project. However, while attempting to ru ...

How can I dynamically swap one div with another within the same div using Javascript?

I have a piece of code that I am working with, and I need it to replace every div element whenever a specific div is clicked. function updateContent(target, replacementID) { document.getElementById(target).innerHTML = document.getElementById(replaceme ...

Adjust the size using padding alone

My CSS specifies font size of 14px, line height of 14px, and padding of 7px on the top and bottom. The total should be 28px. When I apply these styles in a div, it results in a height of 28px. However, when applied to a ul li a element, the height becomes ...

Rails offers a unique hybrid approach that falls between Ember and traditional JavaScript responses

My current project is a standard rails application that has primarily utilized HTML without any AJAX. However, I am planning to gradually incorporate "remote" links and support for JS responses to improve the user experience. While I acknowledge that gener ...

Utilizing webpack, gulp, and typescript to efficiently incorporate jQuery plugins

I'm having trouble figuring out the correct way to load third-party libraries that have dependencies on each other. I am using TypeScript and Gulp with either Webpack or SystemJS for my module loader, both of which are throwing similar errors in this ...

Currently, there is a requirement to include past build outcomes in the HTML test report within the playwright

Is there a way to display the previous build status of each test case for every test case? I have been attempting to use test.info() in playwright, but it seems inaccessible from onTestEnd. One option could be to retrieve the previous build data from Jenki ...

Is it possible to insert IE conditionals within functions.php in WordPress?

One common practice is to include the following script in the <head> section specifically for Internet Explorer 9. <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> Wh ...

What is the best way to transfer scope to a callback function in the context of node-mysql?

When running the code below, I encounter an error that says client is not defined: var mysql = require('mysql'); var conf = { 'database':'database', 'user':'user', 'password':'password ...

Unable to render ng-view due to it being enclosed within a comment block

Currently, I am in the midst of developing a single page application which employs Node, Express, and Angular. The layout of my directory follows the typical format of an Express application <app> +--public +--routes +--views +--partials ...

Toggle a DIV's class using jQuery upon clicking a link, then hide the link and reveal the hidden information inside the DIV. This functionality can be applied to multiple

My main objective is to create a product page that showcases multiple product images within the productLayout DIV. When the link within this DIV is clicked, it should add the class pL100, expanding the width of the DIV to reveal hidden content within the h ...

Unable to locate a resolution for the error message "Warning: Task "uglify" not found"

Below is the content of my Gruntfile.js: module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ uglify: { start: { files: { 'js/script.min.js': ['js/script.js&a ...

Jest tests are failing because React is not defined

I am attempting to implement unit tests using Jest and React Testing Library in my code. However, I have encountered an issue where the tests are failing due to the React variable being undefined. Below is my configuration: const { pathsToModuleNameMapper ...

What is the method to reach a named parameter within a function?

Currently, I am building a RESTful web service using Node JS in combination with Backbone JS. Within this service, there is a specific REST method called GET /users/id/:id, where :id represents the user's identification number. The purpose of this met ...

Challenges encountered when attempting to send an array in res.json with the MERN stack

I am facing a challenge while trying to make two separate model calls using the MERN stack. The issue arises when I try to send an array in res.json; extracting the data seems to be problematic. On examining the console log: {data: "[]", status: ...

Store the label's value as a JSON object in JavaScript

I've encountered a recurring question with no satisfactory answers. Can someone please clarify things for me? Let's take a look at a JSON file: { 'soapenv:Envelope': { '$': { 'xmlns:soapenv': 'http:// ...

transferring data to Amazon Web Services using Angular framework

I'm currently facing an issue while trying to send a file to an AWS server using an Angular dropzone. I have my AWS credentials ready, but I am unsure of how to properly make the request. Every time I attempt to drop the file into the dropzone, I kee ...