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

Issue with Bootstrap 5 dropdown menu on mobile devices when not sliding down upon clicking

Important things to know before getting started: Utilizing Django (python) Implementing Bootstrap Additionally, using html and css Steps taken (in sequence leading up to encountering an error): Copied the navbar template from the bootstrap navbar docume ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Encountering issues with accessing the clientWidth and clientHeight references of the DOM in Vue

Issue with 'clientWidth' and 'clientHeight' properties on Vue and Element types. <div class="invoice-step-detail" id="invoice" ref="invoice"> @Component({ name: 'CreateInvoice', co ...

Integrating Javascript and JQuery in Reactjs: A Comprehensive Guide

Currently, I am working with ReactJS and utilizing the Next.js framework. My goal is to implement the provided code snippet in index.js to display data (day, month, etc.). How should I go about achieving this? Here is the code snippet: <script> fun ...

Employing an assortment of data points within a manufacturing facility

Currently, I have a factory that utilizes a JSON file wrapped in a $http.get request for testing purposes. However, this approach is not suitable when working within a SharePoint environment where JSON files are restricted. In the end, the goal is to integ ...

The method for transforming all headers into permalinks with jquery/javascript

I am looking for a way to transform all headers on a page into clickable permalinks using jQuery or JavaScript. Here is the HTML code: $('h3').each(function() { var id = $(this).attr('id'); if (id) { //Check if the element has a ...

After refreshing the page, the data stored in the localStorage array gets replaced

After refreshing the webpage, my localStorage array values are being overwritten. During a session, I am able to update values on the front end, and the array in localStorage gets updated accordingly. However, if multiple inputs are changed during a sessio ...

Center the text vertically within a card using Vuetify styling

I am seeking a way to vertically align text within a card using Vuetify or traditional CSS in a Vue project. Here is my code: <template> <div> <v-container class="my-5"> <v-row justify="space-between"> <v- ...

Transition/transform/translate3d in CSS3 may lead to significant flickering on the initial or final "frame" of the transition (specifically on an iPad)

Hello everyone, I am currently developing a web application specifically for the iPad and I have implemented a CSS3 transition to animate a div, moving it from left to right. Here is the structure of my class: .mover { -webkit-transition:all 0.4s ea ...

Is there a way to automatically advance to the next question in Surveyjs without needing to click the Continue

I'm currently integrating SurveyJs into my web application. The first 3 pages of my survey contain HTML elements that I would like to automatically slide after a few seconds, similar to the functionality on the following sample site using SurveyJS: O ...

While attempting to retrieve images from S3 using the AWS-SDK Nodejs, users may experience issues with downloading

My goal is to retrieve images from AWS S3 using the AWS-SDK for Node.js. Although the file is successfully downloaded and its size appears correct, it seems to be corrupted and displays a Decompression error in IDAT. async download(accessKeyId, secretAcce ...

Is it possible to launch an Electron application by clicking a run button in the VSCode

I'm new to using VSCode and am currently working on an HTML5 app with Electron. I'm finding it cumbersome to switch between windows and enter a command each time I want to test my application. Is there a way to configure VSCode to run my Electron ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Is it possible to leverage Chrome for troubleshooting the reason behind a failure to load a Truetype font?

For my website, I am currently facing a problem with loading a ttf font. The error log only provides a generic message stating that the font failed to load, without any specific details regarding the cause. Interestingly, the font works perfectly fine on m ...

Steps to connect two drop-down menus and establish a starting value for both

In the scope, I have a map called $scope.graphEventsAndFields. Each object inside this map is structured like so: {'event_name': ['field1', 'field2', ...]} (where the key represents an event name and the value is an array of f ...

Conceal the vertical scrollbar while allowing horizontal scrolling to remain enabled

I'm attempting to create a layout with HTML/CSS where there is a div that can be scrolled vertically and horizontally, but I only want the horizontal scrollbar to be visible. The vertical scrolling should be done using the mouse wheel while the horizo ...

How can I display just the time portion of a date in AngularJS?

Hey everyone, I need assistance with displaying only the time value in AngularJS. Check out my Plunker I have fetched the time value using ng-repeat, but I want to display only the time value on my portal. I have tried to display the time value lik ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...

Guide to integrating various HTML files into a single HTML file with the help of Vue.js

Although I am familiar with using require_once() in PHP, unfortunately, I am unable to use PHP in my current project. I attempted to use w3-include from W3Schools as an alternative, but encountered issues with loading my scripts. Even utilizing JavaScript ...