Shamseer Ahammed
Shamseer Ahammed

Reputation: 1947

JQUERY move background with mouse movement

I have a div with class box1 and it has following css properties(I've given a background image of a random pic from the web)

.box1{
  height:600px;
  width:600px;
  position:absolute;
  background-position:center center;
  background-size:150%;
  top:0;
  left:0;
  background-image:url(http://www.slx-photographic.co.uk/wp-content/uploads/2014/03/Photography-Camera-HD-Wallpaper1.jpg);
}

The question is HOW DO I MOVE THE BACKGROUND with movement of mouse using mousemove(); method of jquery? as of now I've come this far with JQUERY and I can't seem to get it to work

$(document).ready(function(){
    $(document).mousemove(function(e){
      var x = e.pageX;
      var y = e.pageY;

        $(".box1").css({
           ' background-position':'  x/2 +"20px" , y/2 + "20px" '
        });
    });
});

I am trying to change the background position related to movement of mouse so it will be helpful if somebody could explain it if this is not how you do it..

Upvotes: 1

Views: 4787

Answers (1)

user31782
user31782

Reputation: 7589

You are having the quotes in jquery css method incorrectly. It should be like:

$(".box1").css({
  "background-position": x/2 + "20px ," +  y/2 + "20px"
});

Also you'd need to callibrate your x and y to distances from left of box1 and top box1 repectively. You could subract box1's positions. This might be what you want: https://codepen.io/chrisboon27/pen/rEDIC

Upvotes: 1

Related Questions