Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
Spiderian

Parallax Mouse Posistion Based on div Offset?

Recommended Posts

I was playing with paralax scrolling and found an old forum post about it following the mouse. The movement works well but I want to replace the pageX with the posistion of the div#viewPort offset. I tried a few things to get it and return it as a var but I couldn't get the doParallax function to read it. Any help is greatly appreciated.

See the Pen ktAaF by Spiderian (@Spiderian) on CodePen

Link to comment
Share on other sites

Hi Ian,

 

There are a few issues in your code.

 

First jQuery's position() method, returns an object, so when you want to use the value of that object you have to reference whether you want to use the top or left position value. Pretty much like this:

var position = $("#elementId").position();

console.log(position);
//returns Object{"top":value, "left":value};

//To use either you have to specify which value

console.log(position.top);//returns top position value

console.log(position.left);//returns left position value

Second, in the mouse event you're referencing the following:

$('#viewPort').mousemove(function(event){
  var bMouse = event.relX / 1.25;
});

This value returns as undefined, basically because your code is trying to access a property of the mouse event that doesn't exist. In order to solve this create a variable in the mouse event handler, that calls to the relX function and also fix the relX function in order to return a value of the position object, like this:

var relX = function (){
  var p = $('#viewPort');
  var position = p.position().left;
  return (position);
}

//then  the mouse event
$('#viewPort').mousemove(
		function(event){
  var mousePosition = relX(),//this will set the variable value to the left of the viewPort element
       bMouse = mousePosition / 1.25,
       mMouse = mousePosition / 1,
       fMouse = event.relX / 0.5;

  			TweenLite.to(backLayer, 1, { css:{left:'-' + bMouse + 'px'}, overwrite:true } );

  			TweenLite.to(middleLayer, 1, { css:{left:'-' + mMouse + 'px'}, overwrite:true } );
			
  			TweenLite.to(frontLayer, 1, { css:{left:'-' + fMouse + 'px'}, overwrite:true } );
			
  			$('#train').css({'left':event.clientX - 200});
		});

Give that a try and let us know how it goes.

 

Rodrigo.

  • Like 2
Link to comment
Share on other sites

  • 3 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×