Skip to content

Instantly share code, notes, and snippets.

@thelevicole
Last active August 10, 2019 10:06
Show Gist options
  • Save thelevicole/01ebf306760c31c8d1b302c6e4912db4 to your computer and use it in GitHub Desktop.
Save thelevicole/01ebf306760c31c8d1b302c6e4912db4 to your computer and use it in GitHub Desktop.
Simple parallax effect

A very simple parallax effect with jQuery

Standard example:

<div class="example-element" data-parallax></div>

Inverted example:

<div class="example-element" data-parallax="invert"></div>

Movement modifier example: Lower the number, the more the element moves (default: 20)

<div class="example-element" data-parallax data-modifier="10"></div>
( function( $ ) {
'use strict';
window.requestAnimationFrame( function animation() {
$( '[data-parallax]' ).each( function() {
const $this = $( this );
const invert = $this.data( 'parallax' ) === 'invert';
const breakpoint = parseInt( $this.data( 'breakpoint' ) || 0 );
const modifier = parseInt( $this.data( 'modifier' ) ) || 20
let _scroll = $( window ).scrollTop() + ( $( window ).height() / 2 );
let _offset = $this.offset().top;
if ( window_width > breakpoint ) {
const parallax = ( _offset - _scroll ) / modifier;
$this.css( 'transform', 'translateY(' + ( invert ? -parallax : parallax ) + 'px)' );
} else {
$this.css( 'transform', '' );
}
} );
window.requestAnimationFrame( animation );
} );
} )( jQuery || window.jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment