Search code examples
jqueryparallaxonmousemove

jQuery parallax moving element on mouse move


I have a small problem. In the code I have, a mouse move event also moves the element on the X and Y axes. What I want to have is to make the element move only on the X axis and stay at the bottom of the page.

I have tried to delete all the strings with Y axis commands, it stops moving element an Y axis but centers the element - it's the main issue, I want it stay at the bottom.

    $(document).ready(function() {
    var movementStrength = 25;
    var height = movementStrength / $(window).height();
    var width = movementStrength / $(window).width();
    $("#top-image").mousemove(function(e){
        var pageX = e.pageX - ($(window).width() / 2);
        var pageY = e.pageY - ($(window).height() / 2);
        var newvalueX = width * pageX * -1 - 25;
        var newvalueY = height * pageY * -1 - 50;
        $('#top-image').css("background-position", newvalueX+"px     "+newvalueY+"px");

    });
});

Thank you.


Solution

  • I'm not sure I understood what you're trying to do exactly, but I think you're trying to keep the #top-image div on the bottom of the page? If yes, you're centering it on the y axis with this line:

    var pageY = e.pageY - ($(window).height() / 2);
    var newvalueY = height * pageY * -1 - 50;
    

    If you want it at the bottom, it should look like this:

    var newValueY = e.pageY - yourImageHeight;
    

    But if you're using background-position, why not just set background-position-x, and keep background-position-y the same?

    $('#top-image').css("background-position-x", newvalueX + "px");