The right way to change element style on an event

In this blog post we’ll demonstrate how to correctly change the element style with JavaScript – depending on which event we’re listening to. As an example we can take the effect of moving the background image inversely in relation to the mouse position. Essentially we’ll listen to the mousemove event and by using CSS3 transform we’ll change the element position.

Listen to event

Since we aren’t able to get the current mouse position with javascript without a mousemove event, we need to listen for the mousemove event and save the current position in our variables.

Move the element

Before the rAf (request animation frame) you’d need to put moving logics of the element into the mousemove event.

If we take a look at FPS when moving the element, we won’t be very pleased for such a simple operation.

Developer Tools

Request Animation Frame

By using rAF we will avoid changing the element position in cases when such is not necessary.Essentially when the browser isn’t able to do so.

Now we can see how rAF has improved FPS.

Developer Tools


The end result with additional improvements such as: better logics of moving, forces the browser to use 3D transform and resize handler.

The conclusion

It’s understandable that rAF has improved FPS but we’ve also separated logics for collecting data about current mouse position and the very moving of elements which will be usable when developing bigger and more complex websites.

That’s it. That’s the right way to change the element style.