Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ce0ed86

Browse files
Exercise 5 solved
1 parent 04b7f81 commit ce0ed86

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

Week1/js-exercises/ex5-catWalk.js

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,27 @@
1-
/**
2-
3-
** Exercise 5: The cat walk **
4-
Starting with an HTML, which has a single img tag of an animated GIF of a cat walking.
1+
"use strict";
52

6-
1. Create a variable to store a reference to the img.
7-
2. Change the style of the img to have a "left" of "0px", so that it starts at the left hand of the screens.
8-
3. Create a function called catWalk() that moves the cat 10 pixels to the right of where it started, by changing the "left" style property.
9-
4. Call that function every 50 milliseconds.Your cat should now be moving across the screen from left to right.Hurrah!
10-
5. When the cat reaches the right - hand of the screen, restart them at the left hand side("0px").So they should keep walking from left to right across the screen, forever and ever.
11-
6. When the cat reaches the middle of the screen, replace the img with an image of a cat dancing(use this URL: https: //tenor.com/StFI.gif), keep it dancing for 5 seconds, and then replace the img with the original image and have it continue the walk.
12-
13-
*/
3+
const firstImg = document.querySelector('img');
4+
firstImg.style.left = "0px";
5+
const walkingCat = "http://www.anniemation.com/clip_art/images/cat-walk.gif"
6+
const dancingCat = "https://media1.tenor.com/images/2de63e950fb254920054f9bd081e8157/tenor.gif";
7+
8+
function catWalk() {
9+
const currentPosition = parseInt(firstImg.style.left, 10);
10+
const centerOfImg = currentPosition + (firstImg.width / 2);
11+
if (centerOfImg > (window.innerWidth / 2) - 5 && centerOfImg <= (window.innerWidth / 2) + 5) {
12+
firstImg.src = dancingCat;
13+
return setTimeout(() => {
14+
firstImg.src = walkingCat;
15+
firstImg.style.left = `${currentPosition + 10}px`;
16+
catWalk();
17+
}, 5000);
18+
}
19+
if (currentPosition + firstImg.width > window.innerWidth) {
20+
firstImg.style.left = "0px";
21+
} else {
22+
firstImg.style.left = `${currentPosition + 10}px`;
23+
}
24+
setTimeout(catWalk, 50);
25+
}
26+
27+
catWalk();

0 commit comments

Comments
 (0)