Search code examples
jqueryhtmlcsspanning

How to smooth the moving of background image?


I've managed to create a moving/panning background image. It looks and works fine in jsfiddle:

http://jsfiddle.net/juhant/jxthp/6/

But when I test it in my browser, the moving is not smooth and the photo freezes at times.

This is the HTML:

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

This is the CSS:

#pageBg {
    background: url('http://enos.itcollege.ee/~rselis/bg_front.jpg') no-repeat 0 0 scroll;    
    height: auto;
    left: 0;
    min-height: 900px;
    overflow: hidden;
    position: fixed;   
    top: 0;
    width: 100%;
    height: 100%;
}

and the jQuery bit:

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

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

What causes this and how can I fix that? Thank you in advance.


Solution

  • It works now on firefox and ie but on firefox it is too sensitive but background-position is now good

                $('#pageBg').mousemove(function(e){
                    var mousePosX = (e.pageX/$(document).width())*100;
                    var mousePosY = (e.pageY/$(document).height())*100;
    
                    $('#pageBg').css({
                        'background-position': mousePosX +'%' + mousePosY +'%'
                    });
    
                }); 
    

    EDITED: You have to change window => document/width/height . Firefox counted not right mousePositions as other browsers do. So there's to way to fix it or leave (window) and detect browser (firefox) and then

    var mousePosY = (e.pageY/$(document).height()); //without 100
    

    Or change (window) for (document) and it works on Chrome, Opera, Firefox, IE, Maxthon and Safari. Smooth as it should for me.