Gears/Cogs effect using HTML5, CSS & jQuery

logoI wanted to implement a gears effect as part of an upcoming web theme for a client and so I got my thinking hat on.

Essentially what I wanted to achieve was to create a set of cogs that rotate in a gears system to match the brand that we created for a company called Manage Your Customer (website to be launched soon).

What I wanted was for the gears in the system to rotate exactly once based on a user scrolling down the page to make it look realistic and natural.

See the gears effect in action here:

With HTML, CSS and jQuery it is possible to fix the position of elements and rotate them based on user interaction such as scrolling.

The first thing so was to figure out how many degrees to rotate based on the users current scroll position.  Within jQuery the total height of a web page or document can be found and also the current scroll position can be found so using both of these we can get a percentage value of how far we have scrolled down the page.

height = $(document).height();
curScrollPos = $(document).scrollTop();
percentage = curScrollPos/height;

To get this percentage then in angle of rotation simply multiply it by 360 to get the degrees by which the cog should be rotated.

The first and third cogs bot rotate in the same direction but the third rotates in the opposite direction so to get the angle of rotation in reverse we simply take the rotation angle obtained above from 360 (an entire rotation). Simples!

In order to invoke the code on user scroll we use jQuery to listen for the event.  Full code follows:

// Control the spinning gears
    var height = $(document).height();
        // Are we moving up or down?
        curScrollPos = $(document).scrollTop();
        degrees = curScrollPos/height * 360; //multiply by 360, hopefully we get full 360 rotation        
        neg = 360 - degrees;
        $('#cog1').css('transform', 'rotate(' + degrees + 'deg)');
        $('#cog2').css('transform', 'rotate(' + neg + 'deg)');
        $('#cog3').css('transform', 'rotate(' + degrees + 'deg)');


View source from the link above to see the full html/css and jquery.

The html set up is simply a div called page as outer container, then div called gears in a fixed position so that it floats as we scroll, and then each individual cog styled through an id in an absolute position within the gears div.  Each cog is a .png file, in our case we have letters on them to match the clients logo.


Leave a Reply

Your email address will not be published. Required fields are marked *