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

Steps for retrieving multiple documents from Firestore within a cloud function

In my cloud function, I have set up a trigger that activates on document write. This function is designed to check multiple documents based on the trigger and execute if/else statements accordingly. I have developed a method that retrieves all documents u ...

Managing array elements in React: removing and duplicating items

One of my tasks is to incorporate a copy and delete button within a table. My goal is to pass the index from the map to the delete and copy onclick functions, however, I am encountering an issue where copying a row results in it having the same index as th ...

Stop Ajax requests when there are blank spaces in Typeahead.js

I've been experimenting with typeahead.js and utilizing the BloodHound remote feature to load data. Everything is functioning properly, except that when I input only spaces in the textbox, typeahead still makes an ajax call. I'm wondering if th ...

When attempting to render a base64 string in an <img> tag using ReactJS, an error message ERR_INVALID_URL is displayed

I am currently working on displaying server-generated images (specifically matplotlib graphs) in a ReactJS module without needing to save the files on the server. To achieve this, I decided to use base64 to create an image string. When it comes time to sh ...

Automatically open the Chackra UI accordion upon page loading

Currently, I am working on developing a side menu with accordion functionality in Nextjs. I have managed to get the index values from 0 to 1 based on the page URL, but I am facing an issue where the accordion is not opening as expected. Each time a user ...

Encountering a JavaScript runtime error while trying to access and interpret JSON

Currently, I'm facing a challenge with converting a C# list of string types into a JSON object. The issue arises when trying to read this JSON object later in JavaScript. On the other hand, the process seems to work fine when dealing with a C# list of ...

Encountering an issue with Next.js React SSR using styled-jsx: unable to access the 'state' property as

I've come across a problem that I can't seem to figure out. Despite my attempts to search for a solution here, I haven't been able to help myself. I'm new to javascript and react, so please bear with me. Issue: I'm using React (1 ...

Saving the initial and final days of each month in a year using javascript

I am trying to create an array of objects that contain the first and last day of each month in the year. I have attempted a solution but have hit a roadblock and cannot achieve the desired results. module.exports = function () { let months_names = ["j ...

Display the picture for a few moments, then conceal it. A button will appear to reveal the following image after a short period

For my project, I want to create a webpage for school where I display one image that disappears after 5 seconds, followed by a button. The user must click the button before the next image appears and stays for another 5 seconds. This sequence repeats each ...

Resizing SVG to specify width in pixels and automatically adjust height

I'm having trouble understanding how SVG works. Can someone explain where my mistake is? Here's an example of my inline SVG code: <div style="width:1000px; height:auto; background-color:blue;"> <svg class="_image"><use xlink ...

Unexpected element layout issues

Attempting to create a basic website that utilizes the flickr api, retrieves photos and details, and displays them using bootstrap. However, there seems to be an issue that I am unsure how to resolve. Currently, my code is functioning like so: https://i.s ...

Tips for designing a search bar using Angular

search : ____________ I am interested in designing a search bar functionality that automatically triggers when the user inputs 8 or more characters. The input text will be stored in a variable, the search bar will be reset, and the backend API will be che ...

Tips for creating a responsive tab indicator in Material UI?

I successfully integrated react router with material-ui and the routing system is working as expected. Clicking on a tab routes you to the corresponding component. However, I am facing an issue where the blue underline indicator that typically accompanies ...

Several SVG Components failing to function properly or displaying differently than anticipated

I've encountered a puzzling issue that I just can't seem to solve. Here's the scenario: I'm working on a NextJS App and have 5 different SVGs. To utilize them, I created individual Icon components for each: import React from 'reac ...

Successful PHP submission confirmation

I have implemented a basic PHP script on my website to handle email sending. <?php $headers ="From:<$from>\n"; $headers.="MIME-Version: 1.0\n"; $headers.="Content-type: text/html; charset=iso 8859-1"; mail($to,$su ...

Transmit information from Ajax to CodeIgniter's controller

Right now, I am facing an issue with sending data from my JavaScript to a function in the controller using AJAX. Despite my best efforts, AJAX is not sending the data. Below, you can find the code that I have been working on: The JavaScript Function var ...

Is it possible to serve CSS using relative paths that go beyond the URL root?

I've encountered a file path issue with my HTML and CSS files. My HTML file is located in: src/test/html/index.html And the corresponding CSS file is in: src/test/css/index.css In the HTML file, the CSS is linked using: <link rel="stylesheet" ...

Guidance on exporting an Excel file from an HTML table, excluding the final row, using JavaScript

I'm able to export an Excel file from an HTML table, but I'm facing an issue where the last row (tr) meant for pagination on the screen is also being included in the exported result. How can I exclude this row from showing up in the Excel file? ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

Issues with zDepth functionality in Material-UI (React.js) not being functional

Can anyone explain the concept of zDepth to me? I have a component with the following render method: render() { return ( <div> <AppBar zDepth={2} title="Some title" iconElementLeft={<IconButton onClick={this ...