Efficient way to implement hover and click features on an SVG map using jQuery

I have a directory map in SVG format containing around 30-40 listings. I have assigned classes to each location within the map.

Now comes the challenging part,

The objective is to create a tooltip hover effect for each listing that displays the business name and when clicked, directs you to the corresponding page.

While I could individually write jQuery code for each listing, there must be a more efficient way than creating 30 separate click rules and 30 additional hover effects.

Edit: Here is how it currently looks:

$(".location-m1").hover(function(){
    $(".directory-m1").css("display", "block");
    $(".location-m1").css("opacity", ".7");
}, function(){
    $(".directory-m1").css("display", "none");
    $(".location-m1").css("opacity", "1");
});

Link to the Code Example

Answer №1

Enhance the interactivity of your website by incorporating dynamic elements that utilize the class name of hovered elements to access and manipulate other elements.

$(".location").on('mouseenter mouseleave', function(e) {
        var klasses = this.getAttribute('class').trim().split(/\s+/);
    var klass = klasses.filter(function(klass) {
        return klass.indexOf('location-') === 0;
    }).shift().split('-').pop();

    var disp = e.type === 'mouseenter' ? 'block' :  'none';
    var opaq = e.type === 'mouseenter' ? 0.7 : 1;

    $(".directory-" + klass).css("display", disp);
    $(".location-"  + klass).css("opacity", opaq);
});

Check out the demo on Fiddle!

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

How can one determine if a DOM element has been generated dynamically?

Some of the content on this page is dynamically created after an ajax request, while other content was pre-loaded when the page refreshed. When I click on an anchor tag, I need to know if it was created dynamically or not. I did manage to solve this issu ...

Mapping through an undefined array in React causing an error: "map of undefined"

To display an image, title, and description in the browser, the data is stored in an array in a file named customData.js. Below is an example of the data structure: var DATA = [ { name: 'John Smith', imgURL: 'http://whi ...

Ways to efficiently convert HTML form data into JSON format

Currently, I am in the process of developing an ecommerce platform. As part of this project, I have created a billing form to gather essential information such as email addresses and physical addresses from users. The intention behind collecting this data ...

Move from right to left on the slide?

Is there a way to toggle a div's visibility between collapsed and expanded, transitioning smoothly from right to left? I've noticed that most examples I come across demonstrate the transition from left to right. ...

Trigger a functional component's function in React using Chrome developer tools

function App() { const myFunction = () => { console.log('hello world!') } return <div>...</div> } After the website has fully loaded and the component is mounted, can we access the JavaScript to call myFunction()? ...

Using jQuery to measure the height of a div consistently shows a value of 1

I'm attempting to retrieve the height of a specific div using the following code: var divHeight = $("#myDiv").height(); referencing information from the JQuery documentation <div style="width: 300px; height: 300px;"></div ...

Adjusting the size of MUI StaticDatePicker

Struggling to resize the MUI staticDatePicker component. It seems the only way is to adjust the sub-components individually, but I can't locate all of them. Here's what I've managed so far: <Field as={StaticDatePicker} id='bookin ...

Issues with jQuery show and hide functionality are not performing as expected

A dazzling animation has been created, fading in and out gracefully. With two buttons at hand $('.point li') to reveal distinct contents $("#"+classVal+" .table-cell") Nevertheless, upon clicking $('.point li'), I aspire for its conte ...

Sending JSON data along with sendFile() in Node.js and Express done right

After setting up a Node.js server with Express and routing, I am faced with the challenge of passing JSON data onto a specific page ("/users/id") while using sendFile(). While I could make an AJAX request on page load to retrieve the data separately, I am ...

How can I retrieve text that is enclosed within 2 specific tags and then format the output according to my preference?

Is it possible to extract text between specific tags and format the output as desired? Are there any tools or scripts available for this task? For instance: [b]1.[/b] [artist]Norman Bass[/artist] – How U Like Bass? (Warp Brothers Club Mix) [i](3:26 ...

Access information from deeply nested JSON objects and present it in a formatted list using AngularJS

Currently, I am facing a challenge while working on an AngularJS app that utilizes JSON data. As a beginner with Angular, I encountered a point of confusion. Here is the issue: Below is the snippet from the controller: courseController.controller('L ...

Incorporate additional form element functionalities using radio inputs

Recently, I created code that allows a user to duplicate form elements and add values by clicking on "add more". Everything is functioning properly except for the radio inputs. I am currently stuck on this issue. Does anyone have any suggestions on how I c ...

Is it advisable to avoid using jQuery in Angular?

Is it true that using jquery in angular is considered bad practice? I've heard that when needing to manipulate the DOM, one should use directives. But why is it advised against to directly use jquery in the controller?? ...

Move the image inside the box without directly following the mouse cursor, but at a slightly faster pace

I am facing an issue with a Vue component that allows me to zoom in on an image and move it around the container. The problem is, when the image is zoomed in, it moves faster than the mouse due to using the scale transform. Additionally, I noticed that cl ...

Acquire the nested object within a MongoDB document using its assigned ID

Looking to retrieve and edit a specific comment within a post, but not sure where to start. Here is an example of my Post data structure: { "title" : "First Node.js App", "body" : "testing 123", "st ...

Ending a div tag inside another div element

I have set up a listings page with individual divs for each listing, loading content from a separate php script using $.post The issue I'm facing is hiding the listing, possibly related to this line of code: $('div.close_listing') I can o ...

Uh oh! The request couldn't be processed due to a 404 error in the Node.js and Vue.js environment

I find myself a little lost and could really use some guidance. I've created an HTTP server using Node.js, and I'm making an HTTP request from Vue.js to the server. However, I keep receiving the following error: Error: Request failed with statu ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...

Optimizing the JSON date structure

After receiving a datetime value in JSON with the format: Created "/Date(1335232596000)/" I developed a JavaScript function to display this value on the front end. Here's the code snippet: return new Date(parseInt(date.substr(6))); However, the c ...

How to access a scope variable from a script in AngularJS

I'm currently working on a project using AngularJS and TimelineJS3, but I've hit a roadblock. In my application, I have a state called timeline, which has a partial view named timeline.html linked to a controller. This state initializes a promis ...