What is the technique for causing this element to move in reverse?

How can I utilize JS to halt the interval and direct the alien to move backwards once it reaches 700px? I am aware that CSS can achieve this, but I prefer a strictly JS approach. I am struggling with stopping the interval as it hits the left position of 700px...

var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";


var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";

function flow() {
  var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
  alien.style.left = left + 2 + "px";
}
interval = setInterval(flow, 10);

function stop() {
  var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
  if (left > 700) {
    clearInterval(interval);
    alien.style.left = left - 10 + "px";
  }
};
setInterval(stop, 10);
* {
  padding: 0;
  margin: 0;
}

.game {
  background: black;
  height: 100vh;
}

.character {
  position: absolute;
  top: 490px;
  left: 440px;
}
<div class="game">
</div>

Looking for some guidance here!

Answer ā„–1

Implement a velocity variable that will toggle between 2 and -2 once it reaches the right limit. Repeat this process for the left side, switching the velocity from -2 to 2.

Since continuous movement is desired, the stop function becomes unnecessary.

var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";

var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";

let velocity = 2;

function move() {
  var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
  if (left > 700) velocity = -2;
  else if (left <= 0) velocity = 2;
  alien.style.left = left + velocity + "px";
}
interval = setInterval(move, 10);
* {
  padding: 0;
  margin: 0;
}

.game {
  background: black;
  height: 100vh;
}

.character {
  position: absolute;
  top: 490px;
  left: 440px;
}
<div class="game">
</div>

Answer ā„–2

To adjust the position of your element, you can use left + 2 to ensure it consistently moves in one direction.

Once it reaches the 700px mark, you'll need to change it to left - 2 until it returns to 0.

In the code below, I've included a new variable called currentDirection:

var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);

var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);

var currentDirection = 1;
var hasMoved = false;

function flow() {
  var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
  alien.style.left = (left + 2 * currentDirection) + "px";
}
interval = setInterval(flow, 10);

function stop() {
  var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));

  if (left > 700) {
    currentDirection = -1;
  } else if (left < 0) {
     currentDirection = 1;
  }
};
setInterval(stop, 10);
* {
  padding: 0;
  margin: 0;
}

.game {
  background: black;
  height: 100vh;
}

.character {
  position: absolute;
  top: 490px;
  left: 440px;
  background: gold;
  height: 20px;
  width: 20px;
}

.alien {
  background: red;
  height: 20px;
  width: 20px;
  position: absolute;
}
<div class="game">
</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

There was an issue with the Google Maps embed API that resulted in an error with interpolation

My goal is to utilize the Google Maps API in order to showcase a map using data from a JSON file. However, whenever I attempt to incorporate the JSON data, an error message 'Error: [$interpolate:noconcat] Error while interpolating' pops up. < ...

Using Bootstrap classes within a specified class declaration

Can you nest style classes within a single class? For example: .my-upper-class{ .hidden-md, .hidden-sm, .hidden-lg} ...

Guide to creating animated sections using only CSS as you scroll the webpage

I am searching for a method to add animation effects (using @keyframes, transform...) to certain elements as the user scrolls down the page. For instance: When the offset is 0: the div will have a height of 100px. When the offset is between 0 and 100: th ...

Incorporating Distinct Items into an Array with JavaScript

There is a Filter object that stores information about different Car Types. The data is fetched via AJAX calls - on the first call, objects 0-10 are created and added to an array. Subsequent calls bring more car types which are also appended to the array. ...

Traverse div elements using jQuery and showcase the text within them

I've got a setup like the one below. I want to use jQuery to grab each link and display its href right below it. Instead of writing code for each div individually, I'm looking for a solution that works for all divs with the 'col' class, ...

What are the typical situations in which Node.js is commonly used?

Do you believe that a majority of node.js users primarily utilize npm? What do you think are the most prevalent use cases for node.js apart from npm? ...

Obtaining a result from a Promise in AngularJS

Here is a snippet of an Angular JS Service that I have: 'use strict'; app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) { var out = ...

Guide to creating unit tests for document.URL in Angular 5 specifications

Currently attempting to simulate document.URL = 'dashboard'; however, encountering an issue where it states that I can't assign to url because its readonly property. This problem arose while writing jasmine test cases click here for image de ...

Is it possible to process HTML and JavaScript as a request in JMeter?

After receiving a response, I noticed that the HTML body contains a hidden form along with an internal JavaScript function to submit the form (view snapshot here). Is there a method in JMeter to execute JavaScript code that directly submits a form? I am ...

Click-o-Meter: Tracking Button Presses

Iā€™m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet: <?php $counterFile = 'path/to/counter.txt' ; ...

Automatically execute JavaScript upon loading the page with the option to value run on

Upon loading the page, Week 1 is automatically selected which is great. However, the javascript function only runs when I manually choose an option. I want the javascript to automatically trigger for week 1 without needing manual selection. Any ideas on ...

Combining multiple data sources into a single input field in VueJs

I've been exploring the idea of incorporating multiple values into a vue form input binding Here's an example snippet of my code. <template> <div> <label for=""> Employee </label> <input class="form-contro ...

Angular does not display a loading indicator in the header

When handling service calls, I have implemented a loading indicator to provide feedback to the user. However, it appears that this indicator is not effectively preventing users from interacting with header items before the loading process is complete. My ...

Issue with iPhone CSS displaying differently on mobile devices

The CSS design does not display correctly on iPhone devices in real-life testing, even though it appears fine on browsers with mobile view emulators. Interestingly, the design also looks great on Android phones but encounters issues specifically on iPhones ...

Incorporating JavaScript/jQuery values into C# backend with ASP.NET

Despite attempting all possible methods, I am unable to pass the screen.width value from a JS script on an aspx page to C# in the code behind. Even though the screen.width is correctly assigned, it never gets passed to my hidden field value. <asp:Conte ...

Building a hierarchical tree structure using arrays and objects with Lodash Js

I am attempting to create a tree-like structure using Lodash for arrays and objects. I have two arrays, one for categories and the other for products, both with a common key. The goal is to organize them into a tree structure using string indexing. let ca ...

Is there a way to send map data using props in React?

I just want to store and pass the current props.url to the videomodal so I can show the same active video on the video modal. I can't use useState in the map. How can I pass it? Or is there any other solution? Videos.tsx ( props.url must be in the &l ...

Can multiple `npm install` commands run at the same time?

Is it possible to have concurrent runs of npm install, or will they conflict on shared resources and create potential race conditions? Analyzing the code might not provide a clear answer, but for those working on developing npm, this is likely an implicit ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

The response from the Whatsapp-web-js API can be delayed

As I work on creating an API to retrieve groupChat IDs using the express framework and whatsapp-web-js library, I've encountered an issue. The initial request to the endpoint after starting the server yields a response within 31 seconds, but subsequen ...