📜 ⬆️ ⬇️

60 FPS? Easy! pointer-events: none!



You’ve probably already read an interesting article about how you can turn off effects :hover when scrolling - it allows you to keep the site responsive, but it has one drawback - you have to rely on one general class, and this is bad.

 .hover .element:hover { box-shadow: 1px 1px 1px #000; } 

Bad, because this approach limits your extensibility, and introduces extra specification into the already difficult CSS selectors.
')
The trick here is that when scrolling, you simply remove the .hover class from the body tag, thereby turning off all your selectors with :hover . After the end of the event, the class returns, and the effects :hover back in business.

Cool. But not so much - the usual switching of a global class starts a considerable recalculation of styles, and this is not gud. The ingenious solution offered by Christian Schaefer:



Oh yes, pointer-events are our everything!


The pointer-events property allows you to control the conditions under which elements of your page will react to mouse events. See for yourself:



Awesome difference, isn't it? And all this without the extra complexity of selectors:

 .disable-hover { pointer-events: none; } 

Just add this class to our body at the beginning of the scroll, and that's it - the mouse “flies”!

 var body = document.body, timer; window.addEventListener('scroll', function() { clearTimeout(timer); if(!body.classList.contains('disable-hover')) { body.classList.add('disable-hover') } timer = setTimeout(function(){ body.classList.remove('disable-hover') },500); }, false); 

The code, as you can see, is pretty simple. We hang the handler on the scrolling event, in which we first reset the previous timer, check for the presence of a class on our body , and if not, add it. Then we simply add a new timer, which, half a second after the end of the scroll, will reset our class. Everything!

Nearly


If there are elements with pointer-events: auto style on the page, they will grind the global class and will still slow down. We don't want that, right?

 .disable-hover, .disable-hover * { pointer-events: none !important; } 

As you guessed, the solution is just as simple. Super selector * with the flag !important we will teach our elements to behave well.

You can verify the work of this approach. Try to measure performance with hover , and without. The result is impressive!

Source: https://habr.com/ru/post/204238/


All Articles