Citra45Abadi Citra45Abadi - 5 months ago 97
Javascript Question

move image inside a DIV wrapper right/left while mouse hover with Jquery .animate()

I have a wrapper div 400x300 px, and inside I put image with 1140x300px, I want to move the image inside the div, move it to right by 20px, while hovering the mouse, and when mouse is not hovering, the image moves back equals to how much pixels it moved before

for example if I hover my mouse 1s, and the image move just 10px, the image moves back 10px, if I hover 2-3s and image moves 20-30px, it moves back 20-30 px

here's what I created

CSS :

.img-wrp {
width : 400px;
height : 300px;
overflow : hidden;
}

.img {
position : relative;

}


HTML :

<script src="jquery-1.12.4.min.js"></script>
</head>
<body>

<div class="img-wrp">
<img class="img" src="header web 1140.png"/>
</div>

<script>
$(document).ready(function () {
$(".img").hover(
function() {
$(this).animate({"right" : "+=20px"})
};
function() {
$(this).animate({"right" : "-=20px"})
};
);
};
</script>


where is my mistake?

Answer

This should get you started.

Note: 2000 is the speed - move from here to there in 2000 milliseconds

$(document).ready(function () {
  
  $(".img").hover(
    function() {
      $(this).animate({"right" : "640px"},2000);
    },
    function() {
      $(this).animate({"right" : "0px"},2000) 
    }
  );

});//END document.ready
.img-wrp {
  width : 400px;
  height : 300px;
  overflow : hidden;
}

.img {
  position : relative;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <div class="img-wrp">
    <img class="img" src="http://placekitten.com/1140/300" />
  </div>