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

Controlling dropdown menus filled with AJAX responseData

When it comes to Javascript, JQuery has always been a reliable companion for me. However, there are instances where I encounter challenges that require some extra effort to overcome. Today happens to be one of those days. I've stumbled upon an issue t ...

What is the best way to convert a JSON object into a string containing a negative zero in JavaScript?

Is there a way to properly convert a negative zero into a string using JSON.stringify? I've noticed that JSON.stringify often converts negative zero into a positive one, which is not the desired outcome. Any suggestions for an alternative approach? v ...

Having trouble accessing the data I'm setting in a separate component using the Context API

Currently working on my own project and I've encountered a problem while using the Context API. It's my first time using it. The issue I'm facing is that I can't seem to console.log the data I'm setting. I'm trying to create ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...

Tips for positioning an image in the TOP Right corner below the navbar using CSS

I am currently in the process of learning HTML and CSS, and I would like to practice and conduct research whenever I encounter difficulties. Recently, I have been attempting to style my landing page based on a screenshot that I took. However, I have been u ...

Is it possible to display images in PHP when the value matches the specified string?

Is there a faster and more efficient way to display one or multiple images if $value == $string? For instance, let's say I have a cell containing the string 'r o g'. If a user inputs ro, it should output <img src="red.gif"> and <im ...

Dealing with Superagent and Fetch promises - Tips for managing them

Apologies for posing a question that may be simple for more seasoned JS programmers. I've been delving into superagent and fetch to make REST calls, as I successfully implemented odata but now need REST functionality. However, I'm facing confusio ...

Oops! Looks like there was a mistake. The parameter `uri` in the function `openUri()` needs to be a string, but it seems to

While working on my seeder file to populate data into the MongoDB database, I encountered an error message that reads: Error : The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `m ...

Guide to creating dynamic borders around your PHPexcel output

Looking for assistance on adding borders around output arrays in an Excel report using PHPexcel. I reviewed the documentation, but the examples are static, requiring a predefined number to set. My goal is to have all arrays transferred to Excel with bord ...

Navigate to the end of the progress bar once finished

I have a solution that works, but it's not very aesthetically pleasing. Here is the idea: Display a progress bar before making an ajax call Move the progress bar to the end once the call is complete (or fails) Keep the progress bar at 90% if the aj ...

Is it possible for an HTML file to not recognize an external CSS stylesheet?

I've been trying everything, but I can't seem to get these two documents to work together. I'm confident that the CSS file is linked correctly with the right file name. I decided to give it a shot after watching this coding blog tutorial on ...

What is the proper way to format lengthy lines in Twig templates while adhering to coding standards?

In my templates, I have the following code snippet for generating routes with parameters: <a class="btn btn-block btn-abcd" href="{{ path( 'auth.login', { 'type': constant('User::TYPE_CANDIDATE'), & ...

Executing Javascript on Selenium RC with PHP is a crucial skill to have in your toolkit

Is there a way to execute Javascript from Selenium RC? I have been trying different methods with no success so far. I attempted the following approach: I created a custom function in user-extensions.js: function sayhello() { document.write('hel ...

Tips for showing data from Ajax responses on an HTML page

In my code, there are two JavaScript functions: The function fetch_items is responsible for returning data in the form of stringvalue. On the other hand, the function extract_items($arr) passes values to the fetch_items function. function fetch_items ...

Using AngularJS to access form field ids that are generated dynamically

I am dynamically generating form fields using ng-repeat and everything is functioning correctly. However, I now want to incorporate an angular datepicker component that is based on a directive. The issue I am facing is that it only seems to work with stat ...

Find and make adjustments to the primary HTML document in your Magento online shop

Trying to enhance the top banner of my Magento website tamween.biz by adding a shadow effect PNG picture. Successfully managed this on my local server using firebug and creating a new class in the coding area with all selector properties modified in the bo ...

What is the best way to conceal the HTML video controls for multiple videos displayed on a single webpage?

I have a web page that displays a collection of movies generated using a PHP foreach loop. The code snippet looks like this: foreach ($movies as $movie) { $pos = strrpos($movie, '/'); $id = $pos === false ? $movie : substr($movie, $pos ...

Validating a string using regular expressions in JavaScript

Input needed: A string that specifies the range of ZIP codes the user intends to use. Examples: If the user wants to use all zip codes from 1000 to 1200: They should enter 1000:1200 If they want to use only ZIP codes 1000 and 1200: They should enter ...

The search results from the autocomplete feature of the Spotify API appear to be missing

Exploring the Spotify API - I am attempting to implement an autocompletion feature using jQuery for a field that suggests artists as users type. Here is what I have so far: HTML: <input type="text" class="text-box" placeholder="Enter Artist" id="artis ...

Transforming global CSS into CSS modules: A step-by-step guide

In my nextjs project, I am utilizing react-bootstrap and bootstrap which requires me to include the global css: // _app.js import 'bootstrap/dist/css/bootstrap.min.css'; The issue arises when loading a significant amount of unused css on every p ...