Panning a background image in all directions on mouseover using Javascript

Rami Sarieddine picture Rami Sarieddine · Jan 23, 2013 · Viewed 7.7k times · Source

I am trying to add a panning effect to background image in a page, the image is quite large 1800 x 1067 ,so basically will be larger than the window I want to pan the background in all directions when the mouse reaches the end of the window only , I found a Javascript code that does the panning, but only horizontally , tried playing around with it to enable vertical panning. didnt work.

here is the code on JSFiddle: http://jsfiddle.net/v662t/

// HTML

<div id="pageBg">
</div>

//CSS

#pageBg {
    background: url(images/pageBg.jpg) no-repeat 0 0 scroll;
    background-size: cover;
    height: auto;
    left: 0;
    min-height: 768px;
    min-width: 1024px;
    overflow: hidden;
    position: fixed;   
    top: 0;
    width: 100%;
}

// Javascript

$(document).ready(function(){
   $('#pageBg').mousemove(function(e){
      var mousePosX = (e.pageX/$(window).width())*100;
      $('#pageBg').css('background-position-x', mousePosX +'%');
   }); 
});

Answer

georgedyer picture georgedyer · Jan 23, 2013

remove background-size: cover and add a few javascript lines for mousePosY:

var mousePosY = (e.pageY/$(window).height())*100;
$('#pageBg').css('background-position-y', mousePosY +'%');

check out the working fiddle here: http://jsfiddle.net/georgedyer/XWnUA/2/