:active pseudo-class doesn't work in mobile safari

Viewed 100903

In Webkit on iPhone/iPad/iPod, specifying styling for an :active pseudo-class for an <a> tag doesn't trigger when you tap on the element. How can I get this to trigger? Example code:

<style> 
a:active { 
    background-color: red;
}
</style>
<!-- snip -->
<a href="#">Click me</a>
13 Answers

For those who don't want to use the ontouchstart, you can use this code

<script>
 document.addEventListener("touchstart", function(){}, true);
</script>

I tried this answer and its variants, but none seemed to work reliably (and I dislike relying on 'magic' for stuff like this). So I did the following instead, which works perfectly on all platforms, not just Apple:

  1. Renamed css declarations that used :active to .active.
  2. Made a list of all the affected elements and added pointerdown/mousedown/touchstart event handlers to apply the .active class and pointerup/mouseup/touchend event handlers to remove it. Using jQuery:

    let controlActivationEvents = window.PointerEvent ? "pointerdown" : "touchstart mousedown";
    let controlDeactivationEvents = window.PointerEvent ? "pointerup pointerleave" : "touchend mouseup mouseleave";
    
    let clickableThings = '<comma separated list of selectors>';
    $(clickableThings).on(controlActivationEvents,function (e) {
        $(this).addClass('active');
    }).on(controlDeactivationEvents, function (e) {
        $(this).removeClass('active');
    });
    

This was a bit tedious, but now I have a solution that is less vulnerable to breakage between Apple OS versions. (And who needs something like this breaking?)

Related