camila camila - 1 month ago 26
HTML Question

moving background-image on mousemove

I'm trying to make effect that background image moves on mousemove. Now the image does not move, just stay same. Also, I think there is an error on script but I couldn't figure out which part is wrong.



/* background movement by mouse*/

$(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");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<img id="top-image" src="https://static.pexels.com/photos/4164/landscape-mountains-nature-mountain.jpeg">
</div>




Answer

Since you're not using a background image, I don't think you're affecting anything to try to modify the background-position property. Also, I would base the movement amount on the image dimensions, not the window dimensions. Try this:

$(document).ready(function() {
                 var movementStrength = 25;
                 var img = document.getElementById('top-image');
                 var imagewidth = img.clientWidth;
                 var imageheight = img.clientHeight;
                 var height = movementStrength / imageheight;
                 var width = movementStrength / imagewidth;
                 $("#top-image").mousemove(function(e) {
                   var pageX = e.pageX - ($(window).width() / 2);
                   var pageY = e.pageY - ($(window).height() / 2);
                   var newvalueX = width * pageX * -1;
                   var newvalueY = height * pageY * -1;
                   $(this).css("margin-left", newvalueX + "px");
                   $(this).css("margin-top", newvalueY + "px");
                 });
               });
#top-image {
  width: 500px;
  height: auto;
  padding-top:20px;
}

.container {
  width: 600px;
  height: 380px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
TITLE
</div>
<div class="container">
  <img id="top-image" src="https://static.pexels.com/photos/4164/landscape-mountains-nature-mountain.jpeg">
</div>
<div>
Some More Text
</div>