Every click will nudge the square to the right

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>

JS Fiddle link

Answer №1

To achieve the desired effect, you must increment the current value by 100 pixels rather than simply toggling the class to move it right and back.

Ensure that there are no errors in your original fiddle code when implementing this change.

const square = document.querySelector('#square');

square.addEventListener('click', moveRight);

function moveRight() {
  square.style.left = (square.offsetLeft + 100) + 'px';
}
#square {
  width: 100px;
  height: 100px;
  background-color: #333;
  position: absolute;
  left: 0px;
  top: 100px;
  transition-duration: 3s;
  transition: left 1.5s ease-in-out;
}
<div id="square"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Apple Safari 14.0.3 restricts JavaScript from setting a cookie expiry date beyond one week from the current date

This is my second time reaching out with this question, but after plenty of trial and error experimentation, I have gathered much more information to share. I have been attempting different methods to set a cookie in Safari using JavaScript 'document ...

Creating multiple div elements with changing content dynamically

I am facing an issue with a div named 'red' on my website where user messages overflow the 40px length of the div. To prevent this, I want to duplicate the 'red' div every time a message is sent so that the messages stay within the boun ...

What is the best way to utilize Node.js to serve a single page HTML file on port 80?

This is how my project structure is organized: project assets/images/ css/application.css js/application.js font node_modules index.html server.js package.json I am aiming to run 'node server.js" in the project directory and have it serve on port ...

Achieving proper HTML element order?

Here is the HTML page I am working with: Click here to view the code on jsfiddle <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Extended UI</title> <style type="text/css"> .header{ padding-rig ...

Utilizing React: passing a Component as a prop and enhancing it with additional properties

My question involves a versatile component setup like the one below const Img = ({ component }) => { const image_ref = useRef() return ( <> {component ref={image_ref} } </> ) } I am exploring ways to use this compo ...

Improving the style of Google Maps InfoWindows for right-to-left languages

I'm currently working on a Google Maps marker infowindow and trying to adjust the padding specifically for RTL languages. Here's what I've attempted so far: google.maps.event.addListener(marker, 'click', function () { i ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

Unable to redirect using JQuery Ajax post after receiving an ActionResult from an MVC controller

I'm trying to send data from a method to an MVC controller that gives back an action result, and then have my site automatically navigate to the correct view. Here's the code snippet I'm currently working with: function RedirectFunction(ite ...

The background image fails to display properly on the server in Next.js

Hello, I'm currently using NextJs and I have a challenge. I want to set a background image on the body element that is rendered server-side. Below you'll find my code snippets: First, here is my App.js: import BodyStyle from '@components/Bo ...

IE8 is giving me a tough time with CSS3 + HTML5SHIV + CSS3PIE Border-radius; it works fine on IE7, 9, and

Working on a site at , which is constructed using: Twitter Bootstrap HTML5 + CSS3 HTML5SHIV CSS3PIE Problem: Border-radius styling for the navbar link when active is not functioning in IE8 despite using CSS3PIE. However, it works fine in IE7,9,10 (confi ...

The boxslider plugin is malfunctioning when accessed in Sitecore's preview mode

Even though the Boxslider plugin works when we view the page in a browser, it fails to function properly when the same page is viewed in Sitecore's Preview mode. This issue can be replicated by navigating to Presentation in the top menu, then selectin ...

When utilizing row.add in AngularJS and jQuery DataTables, the ng-click function may not function as expected

As a newcomer to angularjs, I have successfully implemented the jQuery DataTable directive with angularJS. However, I am encountering an issue when trying to add a JavaScript function to "TR" dynamically using "ng-click", as it does not seem to be recogniz ...

Create a simple carousel using only vanilla JavaScript, without relying on any external plugins

Currently, I am working on implementing a carousel using plain JavaScript without the use of any plugins. My goal is to have previous and next buttons that will control the sliding images. var firstval = 0; function ...

Displaying the active navigation element in ApyCom JavaScript jQuery menu: tips and tricks

Currently, I am utilizing the jQuery navigation menu from ApyCom. Everything seems to be functioning properly except for one issue. Whenever I click on a different navigation element, I expect that element to remain highlighted in order to indicate to the ...

How to populate the space beneath the `AreaChart` curve in `recharts` when data includes positive and negative values

How can I modify my chart, created using the recharts library in JavaScript, so that the area under the curve fills to the bottom of the visible area instead of stopping at zero? This is how it currently looks: https://i.sstatic.net/CCHXu.png My goal is ...

How do you efficiently include several elements within a single column in Boostrap 5?

I've been working with Bootstrap 5 to display a grid of images similar to this link, but the images are not displaying as intended due to some CSS code. #projects img { width: 100%; height: 100%; } <section id="projects"> ...

Excessive size of bootstrap form

I'm currently working on designing a form within a section that has a width of col-sm-8. The form consists of three columns: label, text input, and username check. I've designated the label to have a width of col-sm-2, the username check to have ...

BreezeJS model, Knockout integration, empty relationships

I am facing an issue where, when using breeze manager.saveChanges(), only the navigation properties are not sent to the server. The rest of the data is being transferred properly. I am relatively new to Breezejs and hoping someone experienced can assist me ...

Tips for increasing the size of a textarea

I'm attempting to extend a textarea by adjusting the margin-top property, but it doesn't seem to be working as intended. Here is the code snippet in question: #sqlcontainerLoggedInPage2 { margin-top: 60px; } <div class="container-fluid" i ...