Question

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 +'%');
   }); 
});
Was it helpful?

Solution

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/

OTHER TIPS

I'm answering the comment about panning at the edges here to include better formatting.

It depends on how exactly you want panning at the edges to work. Will the image move only if the mouse is moving over the edge, or even when the mouse is motionless but hovering over the edge?

In the first case: you can use the same fiddle code and just check to see if mousePosX or mousePosY are < 10 or > 90 (or whatever percentages you want to define as edges). If so, then instead of moving the image to a percentage of the window you'd move it to a percentage of the edge.

Since that may end up a little too sensitive, so you could go with the alternative of just moving on hover, in which case you'd use mouseEnter and mouseLeave events instead, and just start an interval on mouseEnter (using var interval = setInterval(moveImage,250);) that moves the background image a pixel, then clear that interval (clearInterval(interval);) on mouseLeave.

I'll leave it to you to edit the fiddle yourself and see if you can get it working how you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top