Add hover effects on svg rect and nearby elements

Hi!

I’m working on an SVG and trying to add a hover effect on the rectangles. However, due to my limited JS and jQuery knowledge, I’m not sure what functions to use.

What I wanna do is, when the user hovers on a rectangle, the other rectangles surrounding it (let’s say 100 rectangles, and of course the hovered element) changes color with a lower opacity.

Here’s a codepen of what I have so far.
There’s already a hover effect but it only affects the hovered element. Might be hard to notice because the rectangles are very small.

I’ve been searching for hours now, but can’t find whatever function I need to achieve this.

Thank you! :slight_smile:

So it’s going to be a bit of a snarl to do, but here’s the theory to apply:

You know the location of the hovered element. It’s the x and y attributes of the hovered element.

Build an array of objects, by looping through each of the rectangles in the SVG, and determining the distance from the target point (Hint: a^2+b^2 = c^2. Think about what a, b, and c are in this case.). Your objects in this array should have the distance and element as members.

Remove the class from all rectangles.

Sort the array by specifying a function that looks at the object’s distance, and then take the top X elements of your sorted array and apply the class to the element member of those objects.

EDIT: Alternative: Take as many elements as you can, but do so by filtering the array to only those members with a distance less than X.

Additional: Your mouseout should remove the class from all rectangles.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.