Just a small effect, but one I’ve always found rather compelling; created using JQuery, in this case, for speed and simplicity. Very often this effect will be applied to elements given a fixed position on the page: Aaron Harun’s blog has a good example of this, for example. In the case of this article, I’ve made the elements rotate with the page due to space considerations.
The script itself could not be simpler:
$(window).scroll(function() {
var theta = $(window).scrollTop() % Math.PI;
$('#leftgear').css({ transform: 'rotate(' + theta + 'rad)' });
$('#rightgear').css({ transform: 'rotate(-' + theta + 'rad)' });
});
A brief explanation: .scroll
captures the scrollbar being moved, and scrollTop
is how much the scrollbar has been moved down from its uppermost position. %
is the JavaScript modulo operator: that is, it returns the remainder after division of one value (the amount the scrollbar has been moved, in this case) by another (π). The result is then applied to the rotation of an element via a CSS rotate transform, using the slightly unusual (at least in CSS) radians
unit. (1 radian is the arc of a circle with the same length as the radius of that same circle, i.e. just under 57.3 degrees. A complete circle – and thus a complete revolution – corresponds to 2π radians).
So if the scrollbar is moved down 10 pixels, theta
will be whatever is left over from 10 divided by π. 3.14 * 3 is 9.42, leaving 0.58 as the modulus, or a little over 33 degrees as measured in radians. Thus the gears (built using responsive SVG) will rotate roughly 33 degrees with every 10 pixels of page scroll.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/vHBAE