Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS Animating SVG with CSS Transitions and Transforms Rotating and Scaling SVG

Piper Nilsson
Piper Nilsson
858 Points

do these :hover effects work on mobile devices?

is there a way to get these kind of :hover transitions and transforms to work on mobile devices?

3 Answers

Nick Field
Nick Field
17,091 Points

Piper- there is a great stackoverflow thread on a solution to using hover-events and touch-events ( equivalent on mobile/tablet devices ) simultaneously with JavaScript...

Have a read through MacFreeks response on the thread.

To use this in an example with CSS/SVG animations, you could do the following;

  1. Create a class in CSS file with animation/transition properties and values.
  2. Create a JavaScript program with a function to add that class directly to the SVG (in the correct place in the DOM) when it is either hovered over by a mouse OR tapped on by a finger on a mobile/tablet device.
  3. In the JavaScript program, create a function to remove that class when the mouse leaves (is not hovering over) the SVG, or when the user moves their finger after touching the SVG on a mobile/tablet device.

By doing this bit of magic and adding/removing that class, the class will ensure the animations are occurring only when the right mouse/finger behaviour occurs.

Hope that helps :) Nick

Daniel Gauthier
Daniel Gauthier
15,000 Points

Hey Piper,

The :hover pseudo-class needs a pointing device of some form (like the computer mouse's pointer), so while it is theoretically possible for some mobile devices to utilize :hover, it's best to think of the answer as "No, they do not." 99.9% of the time.

Good luck!

Piper Nilsson
Piper Nilsson
858 Points

That's interesting, I will have to test it out! I sort of got something to work using the focus element inside the svg. The <a> tag here makes it clickable, so the animation plays on click, but it is kind of clunky.

<svg version="1.1" width="300" height="200" aria-labelledby="title desc"> <title id="title">Green rectangle</title> <desc id="desc">A light green rectangle with rounded corners and a dark green border.</desc> <a xlink:href="http://example.com"> <rect width="75" height="50" rx="20" ry="20" fill="#90ee90" stroke="#228b22" stroke-fill="1" /> <text x="35" y="30" font-size="1em" text-anchor="middle" fill="#000000">Website</text> </a> </svg>