Having trouble with the position function in JavaScript?

I'm working on creating a small game, but I've encountered some difficulties at the start.

Every time I attempt to obtain the position of track or trackCont, it consistently returns x: 0, y: 0. The DIV doesn't move to the correct position when using:

float: right;
display: block;

and even fails when trying:

position: absolute;
left: 100px;

Below is the code snippet I'm currently using:

var Player = new Array();
var trackEntity;

function getPosition(elem){
    xPos = 0;
    yPos = 0;
    while(elem){
        xPos += (elem.offsetLeft + elem.clientLeft);
        yPos += (elem.offsetTop + elem.clientTop);
        elem = elem.offsetParent;
    }

    return {x: xPos, y: yPos};
}

window.onload = function(){
    trackEntity = document.getElementById("trackCont");
    for (i = 0; i < 4; i += 1){
        Player[i] = new Object();
        document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
        Player[i].entity = document.getElementById("p" + i);
        Player[i].entity.style.backgroundColor = "rgb(" 
                                               + Math.floor(Math.random() * 256) + ", "
                                               + Math.floor(Math.random() * 256) + ", "
                                               + Math.floor(Math.random() * 256) + 
                                                 ")";
        Player[i].entity.style.left = (getPosition(trackEntity).x) + 20;
        Player[i].entity.style.top = (getPosition(trackEntity).y) + 20;
    }
}

http://jsfiddle.net/dh8uf6Lp/

Answer №1

Always remember to include a unit when setting the css left property.

 Player[i].entity.style.left = (getPosition(trackEntity).x) + 20 +"px";   

If you omit the unit when assigning values to dimension or position properties in CSS, they will not update as expected.

The issue may arise because getPosition(trackEntity) is unable to determine its position within the DOM. This problem is typically caused by

document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";

This operation forces the browser to redraw all elements, leading to the loss of reference to trackEntity.

The solution is to avoid injecting HTML using innerHTML and instead create the div element and append it to the DOM.

 Player[i].entity = document.createElement("div");
 Player[i].entity.id = "p" + i;
 //etc.

 document.body.appendChild(Player[i].entity);

 //Execute positioning code.

http://jsfiddle.net/dh8uf6Lp/3/

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

The IDE is showing an error, but Jest is able to run it flawlessly

I recently created a Jest unit test for a TypeScript function called checkEmail, which internally uses showAlert. The showAlert function in the utils.ts file looks like this: export const showAlert = (message: string) => { toast(message); }; In my ...

Steps for inputting time as 00:00:00 in MUI's X DateTimePicker

React:18.2.0 mui/material: 5.10.5 date-fns: 2.29.3 date-io/date-fns: 2.16.0 formik: 2.2.9 I'm facing an issue with using DateTimePicker in my project. I am trying to enter time in the format Hour:Minute:Second, but currently, I can only input 00:00 f ...

Utilizing attributes as scope properties within AngularJS

I am currently working on a directive and I need to pass the Attributes (Attrs) to the $scope, however, I am facing some difficulties in achieving this. Specifically, my goal is to assign attributes in my template based on the name set in my date-picker ta ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

What are some ways to keep the text within the boundaries of the input box?

How can I prevent the letters from extending beyond the bar when typing a lot of characters? Your assistance in resolving this issue is greatly appreciated. <div id="tasks-container"> <div id="tasks-header"> ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Customizing font size in React with Material UI: A comprehensive guide on adjusting the font size of the Select component

I'm currently working on a web application that utilizes React along with Material UI. My goal is to adjust the font size of the Select component. I've attempted to achieve this by utilizing the MenuProps property, as shown in the following code ...

How can PHP be utilized to dynamically add classes to <li> elements and alternate them after every third item

I'm trying to find a way to add a class to an unordered list and alternate that class after every third item. Here's the code I have so far: <?php $i=1; foreach($this->items as $item) : ?> <li class="<?php if ($i % 3 == 0) : ...

Execute an asynchronous function in Javascript, then output the returned data to the console

Is there a way to effectively handle the data returned from an async function? example: JS FILE: async function getData(){ try { $.getJSON('./data.json', (data) => { return data; }); } catch(error ...

Top method for generating a complete object using information from various APIs

I am currently working on an app that consists of a comprehensive form with multiple dropdowns. These dropdowns need to be populated with data from the database. The app utilizes a server with Express, functioning as a proxy: I make calls to it from the fr ...

Is there a way to style alternate iframes using CSS?

I need to select every second iframe in the image provided. Is it possible to achieve this using nth-child? I have tried with the following code (unsuccessfully): #main iframe:nth-child(2n+2) ...

ReactJS Chatkit has not been initialized

I made some progress on a tutorial for creating an Instant Messenger application using React and Chatkit. The tutorial can be found in the link below: https://www.youtube.com/watch?v=6vcIW0CO07k However, I hit a roadblock around the 19-minute mark. In t ...

How to pass an array as parameters in an Angular HTTP GET request to an API

Hey there! I'm relatively new to Angular and I've hit a roadblock. I need to send an array as parameters to a backend API, which specifically expects an array of strings. const params = new HttpParams(); const depKey = ['deploymentInprogre ...

What steps can I take to make sure a jQuery Mobile table does not become responsive?

My goal is to make a table responsive by using media queries to hide optional columns on smaller devices. I need to hide two columns based on different screen sizes: @media screen and (max-width: 33em) { th.optional-1, td.optional-1 { display: no ...

What is the best way to fit the text into a DIV row as efficiently as possible?

Looking for a solution to prevent a span from dropping down to the next line when text is too long within a fixed width and height row. The row consists of three elements, two with fixed widths and the third containing a span and text. Constraints include ...

I am having trouble resolving 'otp-input-react' in my project directory at D:projectappsrc

I have been troubleshooting this issue but haven't been able to find a solution yet. I even tried uninstalling and reinstalling the package, but it still isn't working as expected. Here are some images for better clarity: https://i.stack.imgur.c ...

Use regular expressions to exclude occurrences of the character 'n' from your text

Looking for a regular expression to validate input, specifically filtering out all special characters except "underscore". All characters within the range [a-zA-Z0-9\underscore] are permitted and can appear multiple times. However, my expression shoul ...

Combining both inline and block positioning for div content

My goal with applying CSS styles is to create a visually appealing composition of content: After applying my styles, I received the following result: li { position: relative; list-style-type: none; border: 1px; border-color: red; border-styl ...

The proper method for developing Vue components that are dependent on the parent build tools

In my experience, this issue might also arise in other frameworks with plugin/component ecosystems that rely on specific build tools (such as React components with JSX). While Vue serves as my use-case. Having developed numerous Vue components as single . ...

Take a custom action once all elements have been rendered with ng-repeat

Looking to manipulate a DIV element generated by ng-repeat: <div ng-repeat="data in info" > <div id='plot_{{data.id}}'></div> </div> Here is the sequence of events: Information added to $scope.info ng-repeat exec ...