Reputation: 135
I'm newbie of Javascript and Jquery.
I am learning img animation and I have a question.
If I want to move the image from bottom left to the top right in window. Is there any better way than my code?
My code doesn't' work then I expected.
here is my code
$(document).ready(function () {
function startMoving() {
var img = $("#imageId");
var imgWidth = img.width();
var imgHeight = img.height();
var screenWidth = $(window).innerWeight();
var screenHeight = $(window).innerHeight();
var c = Math.sqrt((screenWidth*screenWidth+screenHeight*screenWidth));
var movement = c/10 // This is for the step of movement
var zScale = (screenWidth+screenHeight)/2;
var imgZScale = (imgHeight+imgWidth)/2;
console.log(zScale);
console.log(imgHeight);
img.animate({
"left": "+="+movement,
"top": "-="+movement
},"slow");
}
setInterval(function(){
startMoving();
},1000)
});
If the image at the corner how can I restart image movement again from bottom left?
Thank you in advance!
Upvotes: 0
Views: 51
Reputation: 4350
You can simplify things using CSS transitions instead of JQuery animate()
. This feature is easy to manage and with less code.
I've just created an initial CSS state and a final stage (.end
), using jQuery to toggle the class to switch from initial/final position.
$(document).ready(function () {
setInterval(function(){
$("#imageId").toggleClass("end");
},2000);
});
img{
position: absolute;
width: 5vw;
height: 5vw;
top: 95vh;
left: 0;
transition: linear 1s;
}
img.end{
top: 0;
left: 95vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="imageId" class="start" width="48" height="48">
Upvotes: 1