Front End, Programming

jQuery background panning in 10 lines of code

$('.panbg').mousemove(function(e){
 //Let's find the midpoints of the screen
 var midpointX = $(window).width()/2
 var midpointY = $(window).height()/2
 //Now the pointer's deviation as a percentage.
 var mousePosX = ((e.pageX-midpointX)/$(window).width())*100;
 var mousePosY = ((e.pageY-midpointY)/$(window).height())*100;
 //Let's dilute it by a factor of 40
 var xPos = mousePosX/40 + 50;
 var yPos = mousePosY/40 + 50;
 //Finally, let's move the background 🙂
 $('.panbg').css('backgroundPosition', xPos+'% '+ yPos+'%');
});
Advertisements
Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s