Tips on accessing the left value of a absolutely positioned object that transitions on click using getComputedStyle or a similar method

Question: How can I ensure that when the target is clicked, the correct and updated value of the left property is returned? For example, I want it to return 120px if --moved is applied, and 100px if it is not applied.

Background: Utilizing getComputedStyle, one can retrieve the values of CSS properties assigned to an HTML element. However, in scenarios where elements utilize absolute positioning, it does not function as anticipated.

Example: In the simplified scenario depicted below, upon clicking the target, the --moved class is either added or removed. Surprisingly, even after this alteration, getComputedStyle continues to provide the initial value of left rather than the updated one post-class modification. This anomaly raises concerns on how to obtain the precise CSS values.

Bonus Point: Upon rapid successive clicks on the target, the returned value often appears fractional, deviating from both 100px and 120px. This discrepancy suggests that when working with absolutely positioned items, getComputedStyle may be returning pixel coordinates rather than the intended CSS values. How might one overcome this dilemma?

const myTarget = document.querySelector('.target');
                const classForMoved = '--moved';
                
                myTarget.addEventListener('click', () => {
                
                    const doesTargetContainAdjustment = myTarget.classList.contains(classForMoved);
                
                    if (doesTargetContainAdjustment === false) myTarget.classList.add(classForMoved);
                    if (doesTargetContainAdjustment === true) myTarget.classList.remove(classForMoved);
                
                    console.log(getComputedStyle(myTarget).left);
                    
                });
.target {
                position: absolute;
                top: 100px;
                left: 100px;
                width: 100px;
                height: 100px;
                background-color: red;
                transition: all 500ms linear;
            }
            
            .--moved {
                left: 120px;
            }
<div class="target"></div>

Answer №1

  • It has been stated clearly that clicking on the element with the class name ".target" will immediately return the current left position.
  • In your code, when you click on the element, a class is added to start an animation. However, since the function is synchronous, it doesn't wait for the transition to complete. As a result, it calculates and returns the current left position immediately.

Remember that setting transition-duration:500ms means the transition of the element with the class ".target" will take 500ms to complete. Therefore, if you call getComputedStyle(myTarget).left after or at the end of the transition-duration (which is 500ms), you will get the expected left value.

  • I have included a promise in the completeAction() function within the click event which will wait for the transition to finish.
completeAction().then((value) => {
    console.log(value)
  })
  • The above code will execute and print out the value.
const myTarget = document.querySelector('.target');
const classForMoved = '--moved';
style = window.getComputedStyle(myTarget)
duration = +style.getPropertyValue('transition-duration').substring(0, 3) * 1000;
myTarget.addEventListener('click', () => {

  const doesTargetContainAdjustment = myTarget.classList.contains(classForMoved);
  const completeAction = () => {
    return new Promise((resolve, rejected) => {
      if (doesTargetContainAdjustment === false) {
        myTarget.classList.add(classForMoved);
        setTimeout(() => {
          resolve(getComputedStyle(myTarget).left);
        }, duration);
      }
      if (doesTargetContainAdjustment === true) {
        myTarget.classList.remove(classForMoved);
        setTimeout(() => {
          resolve(getComputedStyle(myTarget).left);
        }, duration);
      }
    })
  }
  completeAction().then((value) => {
    console.log(value)
  })
});
.target {
  position: absolute;
  top: 100px;
  left: 100px;
  width: 100px;
  height: 100px;
  background-color: red;
  transition: all 500ms linear;
}

.--moved {
  left: 120px;
}
<div class="target"></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

Finding the correct tablet browser resolution for optimal web design

Is there a way to accurately determine the browser resolution for CSS on Samsung Galaxy Tab A 10.1 or other tablets? Despite the specifications stating that the resolution is 1920 x 1200, I am having trouble finding the correct resolution online. As I hav ...

Issues with the parseInt() Function

I'm having trouble figuring out why parseInt() isn't working correctly in my code, especially when passing numbers through to my function parameters. It keeps returning NaN in both my array and the function's return value. What I'm att ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

Enhancing Vue.js Scripts with Laravel Localization Language-Strings

Within my vue.js script, I have successfully implemented a sweetalert using two Laravel localization language strings. Now, I am attempting to utilize the same language strings as data properties in another vue.js component script. The issue arises when t ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

The information does not display in the AngularJS-generated table

Struggling with AngularJS directives? Let's take a look at the code: <div ng-controller="Controller"> <table> <thead> ....... </thead> <tfoot> ....... </tfoot> <tbody> < ...

When splitting a string containing multiple integer values using the delimiter ".", the function in Javascript may return inaccurate results

I need help splitting a JavaScript string using the delimiter "." and extracting an exact integer value. <script> var text = "6.100"; var splitText = text.split("."); console.log(splitText[1]); // I want 100 as the output. </script> ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

Is it possible for search engines like google to index Javascript content that is stored within divs and loaded onto the page?

My website utilizes JavaScript to dynamically add content to div elements, like so: <script> //This content is generated by PHP var contents = [ "Item 1", "Item 2" ]; //Display the first item document.getElementById( "item" ).textCo ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

PHP script for converting HTML lists to plain text

Looking to convert HTML ordered/unordered lists into plain text for export to a txt file? Here's an example: Original HTML: <ol><li>Item 1</li></li>Item 2</li><li>Item 3</li></ol> Desired format: 1. ...

What causes Firefox (Mobile) to zoom out of my webpage?

After launching my webpage on Google Chrome mobile (android), everything loads perfectly. However, when trying to access the site using Firefox mobile (android), most pages load in a zoomed-out view. The issue is resolved by opening the drop-down menu, but ...

Troubleshoot your Vue.js application using Visual Studio Code. Encounter an unidentified breakpoint error

I'm encountering a problem with debugging my Vue.js project using VS Code and Chrome. I followed the official guide on the website Guide, but it's not working for me. The error I keep running into is: unverified breakpoint What am I doing wrong? ...

What is the best way to align an element next to another using id or class?

I am looking to align the search element next to either "Media Heading 1" or "Media Heading 2" based on their id/class. For instance: Assume I have an element with the class of "media-item-1" and I aim to position the search div alongside that element us ...

When the browser is resized, the menus will automatically drop down

I am experiencing an issue with my horizontal menu bar code. The menu bar displays correctly for the resolution 1366 x 768, but when I press the ctrl - shortcut key and reduce the browser size using the same shortcut key, my menus move down. I have tried ...

What is the process of attaching a CSS class to jQuery variables?

Welcome everyone! I am relatively new to CSS and jQuery. In my project, I'm using different CSS classes based on certain conditions within a loop. if(get_node_details[i]['node_status'] == "ONLINE") { var panel_color = ".panel panel-prim ...

What methods would you use to test a Vanilla JS Ajax call handled by a Promise using Jasmine?

I recently came across a great solution on How to make an AJAX call without jQuery? that I wanted to implement. However, I found it challenging to mock the Promise, the AJAX call, or both in my testing. My initial attempt with jasmine-ajax didn't wor ...

searching backwards using regular expressions

I have successfully extracted <%? imagepath;%> using the following regex from a string. <%(\?|.|\s)*%> <img src="http://abc/xyz/<%? imagepath;%>.gif"> <img not_src="http://abc/xyz/<%? imagepath;%>.gif"> <i ...