Last active
January 10, 2022 21:20
-
-
Save vladislavaSim/7b9de1f2bdf91c5d62e42f7dc8307d50 to your computer and use it in GitHub Desktop.
moving square
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>HW</title> | |
<style> | |
.square { | |
width: 100px; | |
height: 100px; | |
background-color: red; | |
position: absolute; | |
top: 15px; | |
left: 0; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="holder"> | |
<div class="square"></div> | |
</div> | |
<script src="main.js"></script> | |
</body> | |
</html> | |
// | |
const $square = document.querySelector('.square') | |
let isActive = false | |
let movingTimer; | |
let step = 1; | |
let x = 0; | |
$square.addEventListener('click', function () { | |
if(isActive && movingTimer) { | |
clearInterval(movingTimer) | |
} else { | |
movingTimer = setInterval(moving, 1) | |
} | |
isActive = !isActive | |
}) | |
function moving() { | |
if(x <= 0) { | |
step = 1 | |
} | |
if( x >= window.innerWidth - 100) { | |
step = -1 | |
} | |
x += step | |
$square.style.left = x + 'px' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment