elementor4fun-logo
Last update: October 10, 2018

Interactive parallax

Step 1

Download and enqueue the file TweenMax.min.jshttps://greensock.com/tweenmax

wp_enqueue_script( 'gsap-js', plugin_dir_url( __FILE__ ) . 'assets/js/TweenMax.min.js', '', '', true );

Step 2

Prepare your design and save all your images separately. All your images must have the same dimension. It's not mandatory but in that way, you don't have to deal with the positions and, more importantly, the 'scene' will still look the same in smaller screen resolutions.

Step 3

Add a Div element and name it 'container'. Change the horizontal item alignment to 'center' :

Step 4

Inside this Div, add a new Div element.

Add a class and change his position to absolute :

Step 5

Inside this Div, add your image (or a text, or a button...actually you can add any kind of element).

So the finale structure will look like this. The first Div is the container, all other Divs have their own class names and they all contain an image :

Step 6

Now it's time to add some CSS to change the order of each elements (if needed) :

.paper { z-index:10 }
.plant { z-index:20 }
.coffee { z-index:20 }
.headphone { z-index:20 }

I just want the 'paper' to be in the background with all the other images in front of it. We can keep the same z-index for the other images, it doesn't matter here.

Note : Never change the value of the z-index in that way :

z-index:1;  z-index:2; z-index:3....

Instead, do something like this :

z-index:10; z-index:20; z-index:30...

The reason is if you have to add a new layer, you can easily add a z-index:15. So you don't have to change the value of ALL the other z-index.

Step 7

And some Javascript :

(function($) {

    $("#container").mousemove(function(e) {
        parallaxIt(e, ".coffee", 30);
        parallaxIt(e, ".plant", -50);
        parallaxIt(e, ".headphone", 20);
        parallaxIt(e, ".paper", 50);
    });

    function parallaxIt(e, target, movement) {
        var $this = $("#container");
        var relX = e.pageX - $this.offset().left;
        var relY = e.pageY - $this.offset().top;


        TweenMax.to(target, 1, {
            x: (relX - $this.width() / 2) / $this.width() * movement,
            y: (relY - $this.height() / 2) / $this.height() * movement
        });
    }

}(jQuery));

If you move your mouse inside the #container, it will run the parallaxIt function for each element we have added.
Here we target some class and we add a number (for the movement effect).

It's the basic function. In another tutorial, we will add more code so we can have more effects (3d rotation).

Source : https://greensock.com/forums/topic/17320-background-parallax-effect-on-mouse-move/

closealign-justifychevron-downcaret-up