Using jQuery to add extra/subtract to background position value based on mouse movement

37 Views Asked by At

I am by no means competent in jQuery, I am good at Googling, but that has only got me so far :(

I have a background image on a full width div. Said background image is positioned using

.no-bg {
    background-position: 86% 93%;
}

I want to add awobble to that background image based on a user's mouse movement.

Googling lead me to find this...

jQuery(document).ready(function() {
var movementStrength = 25;
var height = movementStrength / jQuery(window).height();
var width = movementStrength / jQuery(window).width();
jQuery("body").mousemove(function(e){
          var pageX = e.pageX - (jQuery(window).width() / 2);
          var pageY = e.pageY - (jQuery(window).height() / 2);
          var newvalueX = width * pageX * -1 - 1;
          var newvalueY = height * pageY * -1 - 1;
          jQuery('.no-bg').css("background-position", newvalueX+"px     "+newvalueY+"px");
});
});

All of that works, and it does make the background image wobble. The problem is the background position I set gets overwritten. What I'd like to happen is have the wobble values added/subtracted to/from the 86% 93%. Can the above be tweaked to make that happen or if anyone has some code to achieve this that would be great.

Trying to achieve something similar to this site https://eventlytemplate.webflow.io/

I know they aren't using background images on that site, instead they position imgs inside divs and then translat3d them. I'm retro fitting this effect into a site that is already built so that isn't an option.

Thanks

TJ

1

There are 1 best solutions below

1
K i On

This might work, i haven't tested it.

$(document).ready(function () {
    var movementStrength = 25
    var height = movementStrength / $(window).height()
    var width = movementStrength / $(window).width()
    var bgX = parseInt(getComputedStyle($(".no-bg")[0]).backgroundPositionX)
    var bgY = parseInt(getComputedStyle($(".no-bg")[0]).backgroundPositionY)

    $("body").mousemove(function (e) {
        var pageX = e.pageX - $(window).width() / 2
        var pageY = e.pageY - $(window).height() / 2
        var newvalueX = width * pageX * -1 - 1
        var newvalueY = height * pageY * -1 - 1
        $(".no-bg").css(
            "background-position",
            `calc(${newvalueX}px + ${bgX}%) calc(${newvalueY}px + ${bgY}%)`
        )
    })
})

I've changed the function you've provided a bit. CSS has a calc() function that is helpful in this case

i also used getComputedStyle function from JS to get the original background position values