What is the reason behind the fact that the "transform" property of document.getElementById().style.transform="translateX()" only translates the element once?

I'm currently in the process of developing a new online game. With just a simple click of a button, my goal is to have the red square move horizontally by 50 pixels. Here's a snippet of the HTML code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Cake (2D Singleplayer Adventure)</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
   <script>
      function moveright() {
        document.getElementById("master-cube").style.transform = "translateX(50px)";
      }
    </script>
    <div id="master-cube"></div><img src="arrows/rightarrow.png" alt=h"Right Arrow" height="60vh" width="60vw" onclick="moveright()" class="arrowcontrols">
    <img src="arrows/middlejumpsquare.png" alt="Jump Square" height="60vh" width="60vw" onclick="movejump()" class="arrowcontrols">
    <img src="arrows/leftarrow.png" alt="Left Arrow" height="60vh" width="60vw" onclick="moveright()" class="arrowcontrols">
    </body>
</html>

It's important to note that the images may not load properly. For more details and live demonstration, you can find this project on Repl.it below.

Here's a glimpse at the CSS styles used for this project:

html {margin: none;}

body {margin: none; width: 100vw; height: 100vh;}

.arrowcontrols {float: right; margin-right: 5px; margin-top: 90%; margin-bottom: 10%;}

#master-cube {background-color: #FF0000; height: 40px; width: 40px;}

If you're interested in exploring the interactive version of this game on Repl.it, follow this link: https://repl.it/@ritzcrackerz201/cake

Answer №1

The reason your element retains the transform: translateX(50px) property is that you are setting it to the same value repeatedly, which doesn't change anything.

To see a noticeable change, you must set it to a different value, like this:

let displacement = 50;

function moveright() {
  document.getElementById("master-cube").style.transform = `translateX(${displacement}px)`;
  displacement += 50;
}
html {
  margin: none;
}

body {
  margin: none;
  width: 100vw;
  height: 100vh;
}

.arrowcontrols {
  margin-right: 5px;
  margin-top: 10%;
  margin-bottom: 10%;
}

#master-cube {
  background-color: #FF0000;
  height: 40px;
  width: 40px;
}
<div id="master-cube"></div><img src="arrows/rightarrow.png" alt="Right Arrow" height="60vh" width="60vw" onclick="moveright()" class="arrowcontrols">
<img src="arrows/middlejumpsquare.png" alt="Jump Square" height="60vh" width="60vw" onclick="movejump()" class="arrowcontrols">
<img src="arrows/leftarrow.png" alt="Left Arrow" height="60vh" width="60vw" onclick="moveright()" class="arrowcontrols">

In response to your query about how it functions, here's the explanation:

You need to vary the amount of translation each time. If you repeatedly translate by 50px, there won't be any visible change as it remains fixed at that displacement from its original position.

To observe distinct translations, increment the translation value, for example, by 100px or 150px in subsequent steps. One effective approach is to use a variable to track and update the translation value accordingly.

The syntax

`translateX(${displacement}px)`

makes use of string interpolation, explained here.

Some developers may prefer avoiding global variables due to potential interference from other parts of the code. They might encapsulate such variables locally within a scope to protect them (though not essential at this stage).

If you wish to smoothen the transition effect, consider adding transition: all 1s to the element being translated:

let displacement = 50;

function moveright() {
  document.getElementById("master-cube").style.transform = `translateX(${displacement}px)`;
  displacement += 50;
}
html {
  margin: none;
}

body {
  margin: none;
  width: 100vw;
  height: 100vh;
}

.arrowcontrols {
  margin-right: 5px;
  margin-top: 10%;
  margin-bottom: 10%;
}

#master-cube {
  background-color: #FF0000;
  height: 40px;
  width: 40px;
  transition: all 1s;
}
<div id="master-cube"></div><img src="arrows/rightarrow.png" alt="Right Arrow" height="60vh" width="60vw" onclick="moveright()" class="arrowcontrols">
<img src="arrows/middlejumpsquare.png" alt="Jump Square" height="60vh" width="60vw" onclick="movejump()" class="arrowcontrols">
<img src="arrows/leftarrow.png" alt="Left Arrow" height="60vh" width="60vw" onclick="moveright()" class="arrowcontrols">

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

Applying a gradient overlay to an image using CSS

Feeling a bit frustrated with this issue. I'm working on my Joomla website utilizing Phoca Gallery, and the code it generates includes the following: <img class="pg-image" src="/images/phocagallery/other/thumbs/phoca_thumb_m_something.jpg" alt="So ...

What is the best way to utilize ng-if in the index.html page depending on the URL?

Is there a way to hide certain elements in the index page based on the URL of nested views? In my index.html file, I am looking to implement something like this: <top-bar ng-if="!home"></top-bar> <ui-view class="reveal-animation"> ...

Tips for making a 2D grid on a webpage

Is there a way to implement a 10x10 grid on a webpage where users can click anywhere on the grid and have their (x, y) position recorded with one decimal place accuracy, covering values between 0.0-10.0 or 0.1-9.9? Appreciate any guidance! ...

Node-red occasionally crashes and the JSON output may unexpectedly return HTML content

Having some trouble with my node-red crashing several times a day. I suspect that one of the issues may be related to an http request I am making. I'm trying to retrieve JSON data from a webpage, but sometimes I encounter errors in the log indicating ...

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

"Enhancing Forms with Multiple Event Listeners for Seamless Sub

I'm working on creating a countdown timer with 3 buttons for controlling the timer: start, cancel, and pause. The timer itself is a text input field where you can enter a positive integer. I need to use core JavaScript, not jQuery Start Button: Init ...

Guide on appending a file to a formData object in vue.js

Having trouble adding the file from the input to the formData object. Even after trying multiple solutions, the object appears to be empty when I log it. Can't seem to figure out what's wrong. File Input: <input class="btn btn-sm btn-rounded ...

Adapting Classes in Javascript Based on Screen Width: A Step-by-Step Guide

I'm dealing with two separate menus - one for mobile version and one for PC version. However, the mobile menu seems to be overlapping/blocking the PC menu. How can I resolve this issue? I've attempted various solutions such as removing the mobil ...

The `Target closed` error in Playwright Library is triggered solely by the closing of either the `context` or `browser`

The code snippet below showcases a Node.js script that leverages the Playwright Library for browser automation (not Playwright Test) to extract data from a local website and display the results in the terminal. The challenge arises when the script encounte ...

Using Ajax to dynamically generate column headers in Datatables

Is there a way to create a header title from an ajax file? I've been trying my best with the following code: $('#btntrack').on('click', function() { var KPNo = $('#KPNo').val(); var dataString = & ...

Achieve the effect of bringing the div and its contents to the top when hovered over, all while keeping

I have designed a popup that includes multiple boxes. I want the width of the box to expand and be visible over all content on the webpage when a user hovers over any ".deviceboxes". I tried using ".deviceboxes:hover" which worked fine for the first box in ...

Leveraging nodemailer and handlebars for personalized email templates

I'm encountering an issue and struggling to pinpoint what exactly is causing it. Whenever I execute my code, the following error message pops up: [Error: ENOENT: no such file or directory, open 'C:\Users\Alex\Desktop\emailtes ...

Incorporate a new style into several previous slides using the Slick carousel feature

I'm attempting to utilize the Slick carousel to create a timeline. My goal is for the previous slides to remain colored as you progress through the timeline, and turn grey when you go back. I've tried using onAfterChange and onBeforeChange, but I ...

The functions firebase.auth().currentUser and onAuthStateChanged consistently return null even when the user is logged in

Despite the fact that my front end Swift application indicates that the user is signed in, I am encountering an issue where firebase.auth().currentUser and the onAuthStateChanged listener in my node.js code return null. The backend service is called from t ...

A layout featuring two columns that have heights which are fixed to the bottom of the footer

I've designed a simple layout featuring 2 columns and a footer that adjusts based on the height of the longer column. <div id="holder"> <nav class="navbar navbar-default navbar-fixed-top"></nav> <div class="container"> ...

Steps to establish the starting value as 'Concealed'

I stumbled upon this interesting example that demonstrates how to create expandable/collapsible text when clicked. My question is, how can I initially set the value to be hidden so that the paragraph starts off collapsed and expands only when clicked? He ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...

Utilizing Jquery: Extracting the value of a child element upon clicking the encompassing parent div

I've created a table-like structure using divs instead of tables (because I strongly dislike tables). However, I'm facing an issue. I want to be able to click on one of the div elements and extract the values of its child elements. <div cla ...

How can we make it simple for users to update webpage content using a file from their computer?

I am developing a custom application specifically for use on Firefox 3.6.3 in our internal network. My goal is to dynamically update the content of the page based on a file stored locally on my computer. What would be the most straightforward approach to ...