I have a square that should move 100px to the right when clicked, but on the next click it moves back to the left. How can I resolve this issue?
On JSFiddle, the code works fine. However, when I try to run it in Chrome, I get an error message:
Cannot read properties of null (reading 'addEventListener')
<html>
<head>
<title>JavaScript animation</title>
<style>
#square {
width: 100px;
height: 100px;
background-color: #333;
position: absolute;
left: 0px;
top: 100px;
transition-duration: 3s;
transition: left 1.5s ease-in-out;
}
#square.active {
left: calc(100px);
transition: left 1.5s ease-in-out;
}
</style>
<script>
const square = document.querySelector('#square');
square.addEventListener('click', toggleActive);
function toggleActive() {
square.classList.toggle('active');
}
</script>
</head>
<body>
<div id="square"></div>
</body>
</html>