Issues with Transition not functioning properly with Position properties such as Top, Left, and more

I want to achieve a cool effect where the first li element transitions to the top left corner of the viewport when the page loads. However, whenever I load my page, the element is already in that position instead of smoothly transitioning from its original place to where the drift class places it.

HTML

<header>
    <div class="wrapper">
        <div>
            Header Name
        </div>
        <div>
            <ul>
                <li>
                    item 1
                </li>
                <li>
                    item 2
                </li>
            </ul>
        </div>
    </div>
</header>

CSS

 ul li {
            display: flex;
            text-decoration: none;
            flex-direction: row;
            position: fixed;
            right: 0;
            bottom: 0;
      }
       .drift {
            transition: all 9s linear;
            left: 0;
            top: 0;
       }

JS

    let li = document.querySelector('li');

    window.addEventListener('load', () => {
        li.className += "drift";
    })

Answer №1

If you want to delay the execution of a function, you can utilize the setTimeout method.

Check out the code snippet below:

let li = document.querySelector('li');

window.addEventListener("load", function() {
  setTimeout(myFunc, 1000)
});

function myFunc() {
  li.className += "drift";
}
ul li {
  display: flex;
  text-decoration: none;
  flex-direction: row;
  position: fixed;
  right: 0;
  bottom: 0;
}

.drift {
  transition: all 9s linear slideInFromLeft;
  left: 0;
  top: 0;
}
<header>
  <div class="wrapper">
    <div>
      Header Name
    </div>
    <div>
      <ul>
        <li>
          item 1
        </li>
        <li>
          item 2
        </li>
      </ul>
    </div>
  </div>
</header>

Answer №2

top and left take precedence over bottom and right. This means that when these values are specified, they will override the effects of the properties considered "less important."
Take a look at the demonstration below:

div {
  position: absolute;
  left: 0;
  right: 0;
}
<div>I am positioned both to the left and right,<br>but the left side has priority!</div>

As top and bottom are separate CSS properties, transitioning between them is not possible.
Additionally, since top takes precedence, the transition from an "undefined" state to a newly declared value is not achievable, resulting in CSS immediately applying the final value. (The same applies to left and right)

There are two potential methods to achieve your desired outcome:

  1. Use JavaScript to find either the initial or final value you wish to transition between.
  2. Utilize CSS' transform property for transitioning.

For a CSS-only approach:

  1. Initiate at the bottom-right corner
  2. Transition to the top-left corner using bottom: 100%; right: 100%;. This action positions the element's bottom-right corner on the top-left corner of its parent, effectively placing it outside the parent by its width and height.
  3. Employ the transform property to counteract the overflow caused by step 2, as the percentages used in transform are relative to the element's dimensions, not its parent.

Since transform defaults to values of 0, it can be transitioned without pre-declaration.

View the example below:

// By using 'setTimeout()', the following steps occur:
// 1. The function is placed on the call stack
// 2. The DOM creation continues since the script has executed
// 3. The page initially runs
// 4. The call stack is executed
//
// Step 4 results in: '.drifted' being added after
// the page has been rendered, necessitating the transition
// as a mandatory operation for the rendering engine
setTimeout(() => {
  document.querySelector('div').classList.add('drifted');
}, 0);
html, body {
  margin: 0;
  width: 100%;
  height: 100%;
}
div {
  position: absolute;
  bottom: 0;
  right: 0;
  transition: 2.5s linear;
  white-space: nowrap;
}
div.drifted {
  bottom: 100%;
  right: 100%;
  transform: translate(100%, 100%);
}
<div>I'm drifting!</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

There was a unexpected JSON response from the Django backend that triggered an alert in the Chrome

Trying to send back a JSON file to the Chrome extension for user display. The query is reaching the server without issues, and the fetched URL does return the JSON file when accessed directly. However, the Chrome extension displays an "undefined" message i ...

When a radio button is chosen, multiple text fields must be completed in order to validate the form

I am working with a set of 3 radio buttons. If the last option, labeled "In Home," is chosen, then all 4 of the text fields must be filled in for the form to validate. While I have found information on how to achieve this with checkboxes or a single text f ...

Execute --runTestsByPath on two or more distinct paths

Currently, I am utilizing the jest cli for running my tests. Jest offers a useful cli option known as --runTestsByPath, which allows me to specify the locations of my tests. Despite having unit tests spread out in various directories within my repository, ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Issue with retrieving query results using node_redis client

I've been struggling with a particular issue that I just can't seem to solve. The problem revolves around not being able to retrieve output values from a Redis query. My setup involves using the node_redis client as the Redis driver for my Node.J ...

Having trouble with jQuery loading for the first time

I am having trouble getting the jQuery to load properly. My goal is to toggle classes on specific items identified by their ID. When an item is clicked, I want it to have the class "menu-selected" while the other item has the class "unselected." I have i ...

The mouseup event fails to trigger upon dropping a component with React-dnd

Currently, I am working on a project that requires drag and drop functionality using the React-dnd package. While I have been able to successfully implement this feature, I am facing an issue with the target component where draggable items are supposed to ...

Is there a built-in method that can be used to transform JSON into URL parameters?

Is there a built-in function in JavaScript or the JSON object to convert a JSON object to URL form like: "parameter=12&asd=1"? This is how I have achieved it: var data = { 'action':'actualiza_resultado', ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

notifying users via email in a React application with data saved in Firebase database

In order to notify users of upcoming deadlines, I need to send an email when they are approaching. The deadline is saved in Firebase as a specific date and time (mm/dd/yyyy mm: hh), associated with the user's account email address ([email protect ...

Transitioning classes in Vue elements

Is it achievable to create a smooth transition between two CSS classes with different background images? That's the challenge I'm currently facing. Here is the Vue code snippet I am working on: <div id="flip-list-demo" class="demo"> & ...

Problem with jQuery Window Resize Trigger Not Reactivating

I am facing a challenge in integrating a slider within multiple jquery tabs. As the slider requires specific width and height to display correctly, I have to trigger a window resize event when the tabs are switched. Surprisingly, the code I implemented onl ...

The system detected a missing Required MultipartFile parameter in the post request

Can anyone explain to me why I am encountering the error mentioned above? I am unable to figure out the reason. Below is my code, please review it and suggest a solution for fixing this error. The objective is to upload multiple files to a specific locatio ...

Retrieving a Collection of Items Generated in the Past Day from a Specific Dataset Using JavaScript

I have been tasked with extracting a specific set of arrays from given data based on a 24-hour time frame using the timestamps provided. I initially attempted the code below, but unfortunately, it kept returning the same data to me. I suspect there may be ...

Troubleshooting Compatibility Issues: JavaScript Function Works in Chrome but not in Internet

After collaborating with fellow coders to develop info boxes using HTML, CSS, and JavaScript, I have come across an issue with the hover functionality not working properly in Internet Explorer. Interestingly, everything functions flawlessly on Google Chrom ...

Vuejs application experiencing pagination issues during development

I am encountering an issue while attempting to paginate an array within my vue.js app component. Upon building it, an error is displayed in the vue ui output console: warning Replace `·class="page-item"·v-for="(item,·index)·in·onlineCa ...

npm ERROR: Unable to install the package named "<packageName>" because it conflicts with an existing package of the same name

Currently, I am attempting to incorporate the jsonfile package into my project. However, I am encountering a couple of errors: An issue arises when attempting to install a package with the same name as another package within the same directory. (Despite ...

What could be preventing the background color from changing when attempting to use style.backgroundColor?

My objective is to store the current tab background color in a variable and then use that variable to change the body color. However, for some reason it is not working as expected. Can you help me figure out why? const tabName = 'someId'; var ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

Creating interactive popups using Web Map Service (WMS) with the

I am looking for a way to make a leaflet map loaded from a geoserver interactive by displaying popups with information. Can someone provide a solution using jsfiddle to help me understand? I am struggling to figure out how to achieve this. Essentially, I w ...