Is it possible to preserve CSS transitions while changing the properties being used?

My challenge involves moving a div from left to right on the screen, ensuring it stays aligned even when the window is resized. To achieve this, I dynamically switch between using the CSS properties left and right depending on which side of the screen is closer.

The issue arises with the CSS transition when changing between the left and right properties. While the transition works smoothly when the div moves within the same orientation (either left or right), it instantaneously jumps when switching orientations.

Is there a way to maintain a smooth CSS transition when alternating between using the left and right properties?

I have a JavaScript function:

function moveTimeline(screenIndex) {
    let timelineSectionWidth = (TIMELINE_BACKGROUND_WIDTH - documentElement.clientWidth) / num_timelinePieces;
    
    let isOnLeftSide = (screenIndex < num_timelinePieces / 2);
    
    if (!isOnLeftSide)
        screenIndex = screenIndex - num_timelinePieces;
        
    let new_timelinePosition = Math.floor(screenIndex * timelineSectionWidth);

    if (isOnLeftSide) {
        timelineBackground.css({
            "left": "-" + new_timelinePosition + "px",
            "right": "auto"
        });
    } else {
        timelineBackground.css({
            "left": "auto",
            "right": (new_timelinePosition) + "px"
        });
    }
}

And for the CSS property:

transition: left 1s ease, right 1s ease;

I had hoped for a seamless movement from left to right regardless of which property was in use. However, I am stuck at making it work this way. Trying to avoid using a single property due to potential alignment issues upon window resize, and manual step-by-step movement is a last resort.

Answer №1

When switching from right to left, your transition may appear abrupt because you have set the left and right properties to an auto value. Unfortunately, CSS transitions (or animations in general) do not support properties with an auto value.

According to the documentation on Using CSS Transitions:

The use of the auto value can be quite complex. The specification advises against animating between or to auto. Some browsers, such as those based on Gecko, adhere to this recommendation while others, like WebKit-based browsers, are more lenient. It is recommended to avoid using animations with auto as it may produce unpredictable results depending on the browser and version being used.

You might want to consider using the transform CSS property with the translateX() function instead of relying on the left/right properties. This approach would provide a single, consistent CSS value to transition and deliver better performance.

Your code could be modified as follows:

function moveTimeline(screenIndex) {

  ...

  if (isOnLeftSide) {
      timelineBackground.css({
         "transform": `translateX(-${new_timelinePosition}px)`
      });
  } else {
      timelineBackground.css({
          "transform": `translateX(${new_timelinePosition}px)`
      });
  }
}

Adjust your CSS transition accordingly:

transition: transform 1s ease;

I hope this information proves helpful!

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

What is the best method to add an overlay div onto another div when hovered, with a grid-style layout?

I attempted to create a grid-like design where each div would display an overlay on hover. The overlay div includes two buttons that should be centered. Although I believe the logic of my code is correct, the position of the buttons and overlay is not ce ...

An error occurs stating 'SyntaxError: return not in function' when implementing 'javascript: return false;' within the <a href></a> tag

I've been wrestling with this issue for hours and I just can't seem to crack it. The code works fine in one scenario but not in another. Here's the snippet causing me trouble: <a href="javascript: return false;" name='btnAd ...

The ajax call cannot be processed because the request method 'POST' is not supported

I am currently encountering an issue with making an ajax call to my spring controller for creating some data in the database. The code for the ajax call looks like this: function sendDataToController(param1, param2, index1, index2, dataType) { $.ajax( ...

Exploring Ajax functionality within Datatables

I am attempting to perform an ajax search on a datatable without utilizing the default search functionality provided by datatables. Instead, I have created a textbox with a button for this purpose. My API sends back a JSON response for the JavaScript func ...

Implementing Partial Login and Registration Views using AngularJS in conjunction with MVC5 and ASP.NET Identity

Embarking on the journey of creating a Single Page Application with log-in/register functionality using MVC5, ASP.NET Identity, and Angular feels like diving into a vast ocean of web development technologies. Despite being new to this realm, I delved into ...

Expanding upon Jquery Dialogs with additional dialog openings

I am facing an issue where there is an extra dialog opening after a form submission using the ajaxForm plugin. The content of the dialog is being updated by the ajaxForm function. Below is the JavaScript code that I am using: function formSubmit(target, ...

The width of sibling divs in IE7 does not match their sibling's width

Currently facing a challenge with resolving an IE7 problem. My goal is to ensure that my sibling div has the same width as its counterparts. The initial sibling serves as the header, whereas the subsequent siblings have specific dimensions. Any advice woul ...

What is the best location to include my JavaScript code in WordPress?

Alright, so I've got this world map on one of my WordPress pages and here's an example of the code: <area onmousedown="modifyImage('world_map_01', './images/map/asia.jpg')" onmouseout="modifyImage('world_map_01', ...

What is the best way to generate a list from a text file in javascript?

I have a document called department.txt which lists various departments: Chemistry Physics Mathematics Other I'm looking to generate a dropdown menu <select> in my HTML by importing this file. How can I achieve this using Javascript? There are ...

What is the best way to retrieve the name of a div using JavaScript?

I am having trouble retrieving the div name at alert(name). When I try to get it, all it gives me is "undefined". The values are pulled from a database. Surprisingly, all other alerts in my code are working perfectly fine. Below is the HTML snippet: < ...

What is the best way to remove a specific item from a list of maps in DynamoDB based on a particular attribute value within the

Below is an example of a list I have: { "favorites": [ { "createdAt": 1448998673852, "entityId": "558da3de395b1aee2d6b7d2b", "type": "media" }, { "createdAt": 1448998789252, "entityId": "558da3de395b1aee2d6b7d83 ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Tips for maintaining the fixed positioning of the left and right flex elements (sidebars) as the middle element scrolls, with the scroll bar located on the right side

I am currently designing a webpage with three main elements: a left sidebar, a right sidebar, and a central feed that is 600px wide and scrolls. The scroll bar must be positioned on the right side of the screen, allowing users to scroll by simply using the ...

Remove outdated choices from subcategory menu upon JSON data retrieval

By using the onchange event in the parent dropdown (first dropdown), I am populating the child dropdown (second dropdown). Subsequently, upon selecting an option from the child dropdown, I automatically fill in three text boxes. However, I am facing an iss ...

Retrieve the success return value from Iron-Ajax following a POST request

Currently, I am working on a project using Polymer and I am interested in retrieving the response value from an API after making a POST request with Iron-Ajax. Below is a snippet of my code: var response = $.ajax({ type: "POST", url: apiUrl, ...

Unable to load the CSS file

Having trouble with the folder structure in my content directory: -Content --jquery-ui-1.10.4.custom --------------------------css --------------------------smoothness ------------------------------------jquery-ui-1.10.4.custom.css ----------------------- ...

Take the THREE.js matrix data from an object

I am trying to perform matrix multiplication in Three.js. In my code, I have an Object3D and I managed to retrieve the correct matrix by using console.log like so: console.log(scene.getObjectByName("Pointer").matrix) The output looks something like this: ...

Using Angular 2 HTTP to retrieve a list of file names from a Node backend directory

I am currently attempting to establish a connection between an Angular 2 frontend and a Node/Express backend using an HTTP GET request. The backend should respond by providing a list of file names from a specific folder using the fs.readdir method. I have ...

The inactive submit button due to an unfinished form is not functioning as expected

I am encountering an issue with a form that I have created to add a person to a list. The problem lies in the fact that there must be text entered into the input box in order for the "submit" button to function properly. However, this functionality is no ...

Passing Selectize.js load callback to a custom function

I set up selectize.js to gather configuration options from html data attributes. One of the configurations involves specifying a js function for custom data loading (not just simple ajax loading). Everything was working smoothly until I tried running an as ...