What could be causing my Javascript element to continue moving past 200px?

My code has a "voila" element that is not stopping after reaching 200px. What could be the issue in the logic of the code and how can I fix it?

var voila = document.querySelector(".voila");
voila.textContent = "hahahaha";
voila.style.position = "absolute";


setInterval(function() {
  var left = parseInt(window.getComputedStyle(voila).getPropertyValue("left"));
  if (left >= 0) {
    voila.style.left = left + 2 + "px";
  } else if (left <= 200) {
    voila.style.left = left - 10 + "px";
  }
}, 10);
* {
  padding: 0;
  margin: 0;
}
<div class="voila"></div>

Any suggestions or assistance would be greatly appreciated!

Answer №1

I believe this is what you intended to achieve.

var element = document.querySelector(".element");
element.textContent = "hahahaha";
element.style.position = "absolute";


setInterval(function() {
  var left = parseInt(window.getComputedStyle(element).getPropertyValue("left"));
  if (left >= 0 && left <= 200) {
    element.style.left = left + 2 + "px";
  }
}, 10);
* {
  padding: 0;
  margin: 0;
}
<div class="element"></div>

Alternatively, here is the css method which may work better:

.element {
  x-transition: all 1s ease-in-out;
  animation: anim 1.7s infinite;
  position: absolute;
}

@keyframes anim {
  0% {
    left: 0;
  }
  50% {
    left: 200px;
  }
  100% {
    left: 0;
  }
}
<div class="element">ABC</div>

Answer №2

this specific portion of code else if (left <= 200) doesn't make sense at all

here's a more efficient way to achieve the same result:

const element = document.querySelector('.element');
element.textContent    = 'hahahaha';
element.style.position = 'absolute';
element.animation = { pos: 0, min: 0, max:200, stepOn: 2, stepBack: -10, step: 2 }


setInterval(() =>
  {
  element.animation.pos += element.animation.step

  if (element.animation.pos >= element.animation.max) element.animation.step = element.animation.stepBack
  if (element.animation.pos <= element.animation.min) element.animation.step = element.animation.stepOn
 
  element.style.left = `${element.animation.pos}px`
  }, 10) 
* {
  padding : 0;
  margin  : 0;
}
<div class="element"></div>

You can also utilize requestAnimationFrame() for smoother animations

const element  = document.querySelector('.element')
 
element.textContent    = 'hahahaha';
element.style.position = 'absolute';
element.animation = { pos: 0, min: 0, max:200, stepOn: 2, stepBack: -10, step: 2 }

function moveElement()
  {
  element.animation.pos += element.animation.step

  if (element.animation.pos >= element.animation.max) element.animation.step = element.animation.stepBack
  if (element.animation.pos <= element.animation.min) element.animation.step = element.animation.stepOn

  element.style.left = `${element.animation.pos}px`

  requestAnimationFrame(moveElement)
  }
requestAnimationFrame(moveElement)
*{
  padding: 0;
  margin: 0;
}
<div class="element"></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

Most efficient method for comparing two JSON arrays and rearranging their positions

I am faced with a challenge involving two Javascript JSON arrays. The arrays in question are named this.BicyclePartsOLD and this.BicyclePartsNEW. Both arrays contain an attribute named "ListOrder". The OLD array is currently ordered from ListOrder 1 to n ...

Update app content without requiring users to download a new APK

Hey there, I'm new to all of this so I appreciate your patience. I'm working on a video based app and I'm wondering how I can add new videos/content to the app without having users download a new apk. I know I need to host the app on a data ...

Executing a PHP script

As I work on setting up a html form integrated with php for submitting user data to a database, I'm curious about the best tools to utilize in order to run and successfully test my program. Since it is a php file, what are the most efficient methods t ...

Tips for assigning a value to an Option element when the selection changes in JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http- ...

Guide to installing angular-ui-bootstrap through npm in angularjs application

My goal is to incorporate angular-ui-bootstrap into my project using the following steps: 1. npm install angular-ui-bootstrap 2. import uiBootstrap from 'angular-ui-bootstrap'; 3. angular.module('app', [      uiBootstrap    ]) I ...

Invoking a method in Vue.js from another component

I'm just starting out with VUE and I have a unique challenge for my project. I want to have a button on one page that triggers a function on another page. I know some may ask why not keep the button and function on the same page, but I am exploring ho ...

Incapable of modifying the inner content of a table

I am completely new to AngularJS and struggling with updating the inner HTML of a table. I have a variable that contains a string with three types of tags: strong, which works fine, and nested tr and td tags. However, when I try to replace the table's ...

I am facing an issue with Angular where the $http.get method is

It seems like there must be a small oversight causing this apparently simple problem. I have a function that interacts with the Spotify API to search for an artist. I know that by accessing the corresponding route using a standard URL, a result is returne ...

Pressing the button in the navigation bar results in an expansion of the navbar

Can someone help me figure out why my navbar's height is different from the example on this Bootstrap navigation bar snippet? Here's the code I used: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_navbar_form&stacked=h I copi ...

ERROR: mammoth has not been declared

I've been attempting to integrate the mammoth npm library with my Meteor project. When using the import command, import { mammoth } from "mammoth";, I encountered Uncaught TypeError: Cannot read property 'bind' of undefined After trying ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...

There is a lack of a responsive page after being redirected from Facebook

Having an issue with responsiveness on my website at . When I access a webpage from the browser on my smartphone, the site is fully responsive. However, when I try to open it from a link in Messenger, it appears like the PC version shrunk down to fit a mob ...

Using both ng-if and ng-click in AngularJS for enhanced functionalities

There's a button that should display a toggle only when the value is greater than 0; otherwise, it shouldn't do anything. This snippet of code shows how things were prior to adding ng-if: <span >{{values.valuesNumber}} <i class= ...

When using jQuery, remember to encode square brackets in order to target specific

Imagine an input element <input id="meta[152][value]" type="text" /> In this case, the input field is created on-the-fly. I must choose that particular field. That's why I used, alert($('#meta[152][value]').val()); However, it appe ...

What are some ways to customize the appearance of React Semantic components?

Is there a way to apply CSS for react semantic UI when using create react app? I have installed semantic-ui-react and included the CSS CDN: loginForm.js: import React from "react"; import { Button, Form, Header } from "semantic-ui-react"; import styles f ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Optimal Procedure for New Users Form (Jade / Angular) in HTML

I'm currently working on integrating a form into my app for users to create tasks. This form should only appear the first time a user attempts to create a task. As someone who is not very experienced with frontend development, I find myself wondering ...

Positioning the search bar to the left with react-bootstrap-table

Is there a way to move the search bar of react-bootstrap-table to the left instead of keeping it on the right? You can see an example here, at the bottom of the page: I know that you can create a custom search panel and input, but that seems like a compl ...

unable to display images from a folder using v-for in Vue.js

Just getting started with Vuejs and I have two pictures stored on my website. The v-for loop is correctly populating the information inside databaseListItem. The path is /opt/lampp/htdocs/products_db/stored_images/cms.png https://i.stack.imgur.com/969U7.p ...

Dynamic Form Submission - Displaying Notifications for Success and Failure

While I have managed to successfully submit my form using PHP, I am currently facing some challenges with AJAX. Whenever I submit the form, an error message pops up as if 'res' is false instead of true. Despite my efforts to troubleshoot and rese ...