CSS animation for both mouse hover and touch (iOS)

7.1k Views Asked by At

Here is plnkr example.

Basically there is a style like that

.hover-block {
    -webkit-transition: all 1s linear;
            transition: all 1s linear;      

}

.hover-block:active {
  pointer-events: none;
    -webkit-transform: scale(1.5);
            transform: scale(1.5);
}

.hover-block:hover {
    -webkit-transform: scale(1.5);
            transform: scale(1.5);
}

I'm seeking to support evergreen and IE10/11, Chrome for Android (4.4+), Mobile Safari (iOS 7+), and it shouldn't hurt other touch events (swipe scrolling).

It seems to work as intended on Android and Chrome device emulation, non-sticky transform on touch is desired behaviour.

But somehow this plunker doesn't work on iOS webkit (iOS 8, all browsers), it does nothing on touch. I'm quite sure that exactly the same approach (block element, :active with pointer-events: none plus :hover) worked for me in iOS 8 before. How can it be fixed?


It looks like empty touchstart/touchend JS event handler or ontouchstart/ontouchend attribute can activate touch behaviour on iOS (can't be sure but it is possible that it happened to me before). Is it a known fix for the problem or there are less hacky ones, which iOS versions are affected?

2

There are 2 best solutions below

2
On BEST ANSWER

So the issue you're running into is this: "The :active pseudo class matches when an element is being activated by the user". A standalone <div> element cannot be activated by the user and therefore will not be matched by the :active pseudo class.

If you look under Browser Compatibility in the :active MDN article you'll see that:

[1] By default, Safari Mobile does not use the :active state unless there is a touchstart event handler on the relevant element or on the <body>.

MDN has a list of pseudo classes that can be used and you might be able to find one that better fits your situation or adding a touchstart event should do the trick in Safari.

I was able to get your plnkr working really quick by changing the <div class="hover-block"></div> element to <button class="hover-block"></button> and changing .hover-block:active { to .hover-block:focus {. I also added display: block; border: 0; to .hover-block.

You, for obvious reasons, may not want to change your <div> to a <button> to get your effect to work, but by using an element that can be activated, using a different pseudo class, or adding an event that allows activation in your target browser, you should be able to achieve the effect you're looking for on mobile devices.

Hope that helps!

1
On

In your html, instead of <body>, do <body ontouchstart=""> Or in html5, just <body ontouchstart>