Engaging SVG Experience: Alter the color of one element by hovering over another

I'm currently working on creating an interactive SVG map. I have successfully incorporated code from Illustrator into an HTML file and managed to change the fill color of certain paths when hovering over them. However, I am facing an issue where a white rectangle and text are blocking the interaction with my path elements. My objective is to allow for hover effects on text, white backgrounds, and paths so that the paths always fill in a specific color (#ff7bac).

Below is a snippet of my SVG code:

<a xlink:href="http://travelalberta.com" id="wohnrauemeLink">
    <g id="wohnraeume">
        <g id="wohnraeumeFill">
            <g>
                <path class="eckig" d="M1169,124.5v341.1h429V124.5H1169z M1390.5,445h-199.4l0-68.7h71v33.9h128.4V445z"/>
            </g>
        </g>
        <polygon id="wohnrauemeWhite" fill="#FFFFFF" points="1191.3,445.6 1191.2,372.3 1262.3,372.3 1262.2,410.1 1391,411.3 
            1390.5,445.7                "/>
        </g>
</a>

Here is the CSS associated with it:

path.eckig {
    fill: #FFFFFF;
    opacity: 0;
    transition: .6s fill;
      }

path.eckig:hover { 
    fill: #ff7bac;
    opacity: 1;
     }

I would greatly appreciate any assistance as I have been stuck on this issue for a few days now.

******************** Edit *********************

Hello there :)

I am still trying to resolve this problem, so here is a simplified version:

https://jsfiddle.net/4tjzk8z5/11/

The main goal is to change the color of the red rectangle when hovering over the blue rectangle.

I attempted using JavaScript this time, but unfortunately, it did not work:

function mouseoverblue(){
var myPara = document.getElementById("red");
myPara.style.color = "#123444";

}

Thank you in advance for any help you can provide!

Answer №1

If you have SVG code on your HTML page, I recommend using CSS to create animations.

Check out this jsFiddle for reference

Here is the CSS for your example:

/* Colors the polygon where you are hovering it or the path */
#wohnraeumeFill:hover+polygon,
polygon:hover{
    fill: #800;
}

EDIT

Since CSS cannot select previous siblings, you need to rearrange the order of your SVG elements like so:

<svg>
    <g id="wohnraeume" transform="translate(-1100 -350)">

        <polygon id="wohnrauemeWhite" fill="#FFFFFF" points="1191.3,445.6 1191.2,372.3 1262.3,372.3 1262.2,410.1 1391,411.3 
            1390.5,445.7                "/>
        <g id="wohnraeumeFill">
            <g>
                <path class="eckig" d="M1169,124.5v341.1h429V124.5H1169z M1390.5,445h-199.4l0-68.7h71v33.9h128.4V445z"/>
            </g>
        </g>
    </g>
</svg>

You can then use this CSS rule:

polygon:hover + #wohnraeumeFill path{
    fill: #800;
}

Check out the updated jsFiddle here

Answer №2

In the scenario of using jQuery, the code would look something like this:

$('#svg1').on({
    mouseenter: function () {
        $('#svg2').css('fill', 'red');
    },
    mouseleave: function () {
        $('#svg2').css('fill', 'blue');
    }
});

In this snippet, #svg1 corresponds to #wohnraeumeFill and #svg2 corresponds to #wohnrauemeWhite.

Answer №3

Implement mouse event functions onmouseover to change the color and onmouseout to revert it back.

<rect id="blue" onmouseover="changeColor('#a02e3f')" onmouseout="changeColor('#123444')" x="753" y="375.3" fill="none" width="586.2" height="501.7"/>

Add this script section as well: (Remember to set the Load Type to head)

function changeColor(color){
    document.getElementById("red").style.fill = color;
}

PS: Alternatively, you can utilize JQuery by clicking on this Link Here and selecting JQuery in Frameworks and Extensions.

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

Values on text elements are not present in getBBox()

In my Node.js project, I am using jsdom and Raphael Js to create SVG markup on the server. Everything was working fine until I started noticing missing values when calling getBBox() on text elements in Raphael. var paper = window.Raphael(10, 50, 320, 200) ...

What could be causing justify-content: flex-start; to not function as expected?

Can someone help me with my flexbox navbar? I set the justify-content property to flex-start, but the content inside the container is not aligning correctly. You can see the output and code here: output html, body { backgr ...

How to choose a single checkbox in Ionic 2 and retrieve its value

On my single screen, I have about 20 questions and answers retrieved from a database. To display the options, I am using checkboxes but struggling to implement the desired functionality. What I want is to allow only one checkbox selection out of 4 options ...

Unable to insert JSON data into modal

I am facing an issue with appending Descriptions into modals after fetching data through axios. Each div contains a Category, and clicking on it should open a corresponding modal displaying the Description. Although I can see the Descriptions in the conso ...

Styling components in React using inline styles that are based on JSON values

I'm successfully pulling in JSON data and mapping it within a React component. However, one of the values in the JSON is a HEX code that I want to apply as an inline style for the background color of a div. I have experimented with various methods, b ...

Sign up for and run a JavaScript function within an ASP.NET Page_Load event

Is there a way to both register and run a JavaScript function in ASP.NET during a Page_Load event? I need the function to validate the content of a textbox, and if it is empty, disable a save button. function Validate(source, arguments) { } ...

In Firefox, the parent div's width is greater than the combined width of its children

In Firefox, I am encountering a peculiar problem. The issue arises when I have a div with a height defined in a fixed px value, and an img element nested within it. While this configuration works fine in Chrome, in Firefox, the parent div's width end ...

utilizing vueJS for global notifications

It may sound like a cliché question, but I still haven't grasped it. I have a primary component that is always loaded in the application. Let's refer to it as DefaultContainer.vue <template> <div class="app"> .... Notifi ...

How can I display JSON data as key-value pairs in ReactJS?

Transitioning from JavaScript to React, I've come across some threads that touch on this topic but none quite hit the mark. I have a local JSON file that was created with a Python script, and it looks something like this: [{"hello": 10, "world": 15 ...

Error: The options object provided for CSS Loader is not valid and does not match the API schema. Please make sure to provide the correct options when

Summary My Nuxt.js project was created using the command yarn create nuxt-app in SPA mode. However, I encountered an error after installing Storybook where running yarn dev resulted in failure to start the demo page. ERROR Failed to compile with 1 errors ...

Making a Jquery Ajax Request in Real Time

Is there a way to make sure that the "Test Data" text is only displayed in the console after the book details are fully loaded into vm.books? I am trying to make a synchronous ajax call for this purpose. The code below is not producing the expected result ...

Implement AJAX and javascript to generate a pop-up notification using Django's messaging framework

I recently implemented AJAX validation for an input field on my django site by following a tutorial. While it works well, I want to maintain the use of toasts for user alerts, rather than traditional alerts. $("#id_hub_name").focusout(function (e ...

Incorporate data into the div element

I've been attempting to populate a div after selecting 3 different options from select boxes, but nothing seems to be happening. I have confirmed that the PHP function works as expected when tested manually, but I'm unable to get it to populate a ...

Tips for preventing recursion when utilizing scrollIntoView() in a scroll event handler

My goal is to break down my website into screen-sized sections that automatically scroll to the next section when a user begins scrolling. I attempted to accomplish this by using the following code: $(window).scroll(function() { getElementToScroll().s ...

Is it more suitable for a library used by getStaticProps to be classified as a normal dependency or a dev

When working with NextJS's getStaticProps, I am implementing a library that is only utilized during build time. Should this library be categorized as a regular or development dependency in my package.json? ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Having trouble with selecting JS dropdown options in Python Selenium

My HTML view- Check out the website design HTML code- View the HTML code here When I click on the dropdown arrow, a new code appears - view the code snippet Although my code successfully displays the dropdown options, it does not allow for selecting an ...

Using JavaScript to analyze and handle newlines, spaces, and the backslash character

Hello everyone, I'm hoping things are going well. I am currently working on removing newline and "\" characters from a string that I have after using JSON.stringify(). The string in question appears as follows: "[{\n \"id_profile&bs ...

Adjusting element sizes in HTML5 Canvas

I am currently facing an issue with my canvas container, which has a width of 100% and a height of 50%. When I draw lines on it using x and y coordinates like this: context.moveTo(20, 20); context.lineTo(50, 20); context.stroke(); The problem arises when ...

Integrate the elements from the <template> section into the designated <slot> area

I am trying to retrieve template content, insert it into a custom element with shadow DOM, and style the span elements inside the template using the ::slotted selector. However, it seems like this functionality is not working as I expected. <!doctype h ...