Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encountering issues with this process.

I am starting to suspect whether only one translation can be called on an element within CSS. Although I have not found any documentation stating such restrictions, it seems like this might be the case based on my observations.

The core problem lies in:


function change_level() {
  var level = document.getElementById("level");
  level.parentNode.removeChild(level);
  var ball = document.getElementById("init_pos");
  ball.style.backgroundColor = "orange";
  ball.style.borderRadius = "25px";
  ball.style.transform = "translate(-600%, -647%)";
  setTimeout(ball_movement(ball), 3000);
  ball.style.transition = "background-color 2s ease-in, transform 3s ease";

}

function ball_movement(ball) {
  var movements = 5;
  var x;
  var y;
  for (var i = 0; i < movements; i++) {
    x = getRandomArbitrary(-800, 800);
    y = getRandomArbitrary(-800, 800);
    ball.style.transform = "translate("+x+", "+y+")";
    ball.style.transition = "transform 3s ease";
    console.log(x);
  }
}

I have shared the code on jsfiddle, but due to the canvas size differences, the calculations are not functioning as expected.

Check out the JS Fiddle here

Answer №1

It seems like there are a couple of adjustments that need to be made to your code:

  • When specifying the transform value in the ball_movement function, make sure to include units (such as pixels or percentages) for the x and y variables instead of just numbers. You can append px or % to the string accordingly.
  • When calling the timeout function with ball_movement(ball) as the first parameter, it will execute immediately. To prevent this, enclose it within an anonymous function.

Please note: I have adjusted the initial values for the translate function and random number calculation in the provided snippet to ensure the ball movement stays within boundaries.

window.onload = function() {

  var
    html_display = {
      0: "Level One",
      1: "Level Two",
      2: "Level Three",
      3: "Level Four",
      4: "Level Five"
    };

  html_key = 0;

  //remove level offscreen and add ball
  function change_level() {
    var level = document.getElementById("level");
    level.parentNode.removeChild(level);
    var ball = document.getElementById("init_pos");
    ball.style.backgroundColor = "orange";
    ball.style.borderRadius = "25px";
    ball.style.transform = "translate(-150%, -150%)";
    ball.style.transition = "background-color 2s ease-in, transform 3s ease";
    setTimeout(function() {
      ball_movement(ball);
    }, 3000);

  }

  function ball_movement(ball) {
    var movements = 5;
    var x;
    var y;
    for (var i = 0; i < movements; i++) {
      x = getRandomArbitrary(-100, 100);
      y = getRandomArbitrary(-100, 100);
      ball.style.transform = "translate(" + x + "px, " + y + "px)";
      ball.style.transition = "transform 3s ease";
    }

  }

  function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
  }

  function intro_html() {
    document.getElementById("level").innerHTML = html_display[html_key];
    setTimeout(change_level, 1000);
  }

  intro_html();
}
body {
  position: absolute;
  top: 45%;
  left: 50%;
  -moz-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}
#level {
  font-family: helvetica;
  font-size: 29px;
  position: absolute;
  top: 45%;
  left: 50%;
  -moz-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}
#init_pos {
  position: absolute;
  top: 44%;
  left: 48.17%;
  height: 50px;
  width: 50px;
}
.container {
  height: 700px;
  width: 1100px;
  top: 45%;
  left: 50%;
  border: 4px solid black;
  overflow: hidden;
}
<div class="container">
  <p id="level"></p>
  <p id="init_pos"></p>
</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

Press the button to access the URL within the current window

Working with Angular, I attempted to develop a function to open a URL in the current window. However, the code below within the controller actually opens a new window: $scope.openUrl = function(url) { $window.open(url); }; ...when using ng-click=&apo ...

Angular - CSS Grid - Positioning columns based on their index values

My goal is to create a CSS grid with 4 columns and infinite rows. Specifically, I want the text-align property on the first column to be 'start', the middle two columns to be 'center', and the last column to be 'end'. The cont ...

Retrieve the value of a PHP array within a for loop and transfer it to JQuery

*edited format I came across a PHP code for a calendar on the internet and I am currently working on implementing an onclick event that captures the date selected by a user as a variable (which will be used later in a database query). At this point, my g ...

Can JavaScript be used to determine if any code has been executed from the browser's console?

I'm currently developing a JavaScript game and I want to prevent cheating. Is there a way for me to track and record commands entered in the JavaScript console? Here's a basic outline of what I have in mind: consoleCommands = ""; window.console ...

Error: Missing 1 type argument(s) in generic type definition

I've developed an abstract class structure as shown below: export abstract class CsvFileReader<T> { data: T[] = [] constructor(public file: string) {} abstract mapRow(row: string[]): T read() { this.data = this.file .split(& ...

Exploring the possibilities of combining OpenCV with web technologies like Javascript

I am currently faced with the challenge of integrating OpenCV into a web application using Express.js. While I am familiar with the Python and C++ libraries for OpenCV, I now need to work with it in conjunction with Express.js. My main requirements include ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Utilizing Various jQuery Selectors for Option Values

I'm currently facing a challenge with including extra value selectors in jQuery. My goal is to include option[value="18:00"] so that if option [value="17:00"] is not chosen, it will trigger the function when 18 is selected. Below is the code snippet: ...

Leverage the power of personalized SCSS styles in combination with Bootstrap-Vue, Webpack, and

I have been working on an application using VueJS with Bootstrap-Vue and I encountered a challenge while trying to import a SCSS file to customize the Bootstrap variables and add some custom styles. Here are the steps I have taken so far: Installed node ...

The property 'enabled' is not a standard feature of the 'Node' type

Within the code snippet below, we have a definition for a type called Node: export type Node<T> = T extends ITreeNode ? T : never; export interface ITreeNode extends TreeNodeBase<ITreeNode> { enabled: boolean; } export abstract class Tre ...

Customized Box with MaterialUI Styling

Currently, I am utilizing Material UI 5 for my project. To avoid repeatedly defining the same sx prop every time I create a box, I aim to build a custom box component that ensures all boxes have a consistent appearance. Upon going through the documentation ...

Tips for sending parameters using arrow functions within ReactJS hooks

I've recently started working with ReactJS and I'm a bit confused about how to pass parameters using arrow functions. I attempted to use .bind() in order to bind the value so it can be used in the function, but unfortunately that didn't work ...

Progressive rendering of particles in THREE.js

I am new to the world of 3D and I'm trying to render particles as they are created. My goal is to have these 2000 particles render individually as they are created, but with the current code, they only render once all particles have been created. I h ...

Tips for retrieving return values from AJAX URL content

As I am writing some code to send data from one page to another through the ajax URL, I encountered an issue where the retrieved values on the previous page are showing as null. The first page code looks like this: <script> function myFunction() { ...

Loading 500,000 entries individually into mongodb results in a memory overflow

I am currently working on inserting a large volume of 500,000 records into a MongoDB collection. These records are stored in a CSV format, parsed, and then saved to an array. I am using a recursive function to insert the records one by one, and when a reco ...

"Utilizing a media query to display an anchor link at the top based

How can I create a "Back to Top" link that automatically scrolls mobile and tablets to the top of the page? Usually, I would achieve this using JavaScript by detecting the window and body height. Is it possible to accomplish this using a media query? @me ...

Fill in the select dropdown menu

I am trying to trigger the population of a select dropdown when the user clicks on it. The issue I am facing is that the click handler seems to be activated only when the user clicks on the options within the select, whereas in my case there are no optio ...

Obtain the selected option's value using Angular

Having an issue with my user.model.ts file. I have a list of users that I can edit by clicking on a button that filters the user's data and puts it in a bootstrap modal. I'm using [ngModel] in a select tag to get the country of my user, but when ...

Is it possible to remove a particular div after clicking the delete button, especially if multiple divs are displayed upon clicking the add

var count = 2; var countMax = 5; function adddt() { if (count > countMax) return; document.getElementById('dt-' + count + '').style.display = 'block'; count++; } <link href="https://maxcdn.bootstrapcdn.com/bo ...

The float:left property within a div is not behaving as anticipated

I am having trouble positioning my second div. In order to have 70% of my website for posts and 30% for a small text display, I created a new div. I believe the correct way to position it is by using "float: left" so that the div goes under the banner whe ...