Animating or transitioning CSS keyframes to an inline value when the page is initially loaded

In my current project, I am working on creating HTML and CSS-based bar representations of percentage values. The structure of the code is as follows:

Using HTML:

<div class="chart">
  <div class="bar" style="width:43%"></div>
</div>

With CSS styling:

.chart {
  background-color: #DADADA;
  height: 2px;
  position: relative;
}

.chart .bar {
    background-color: #3D98C6;
    height: 100%;
}

The goal I have in mind is to initiate the bar width at 0% upon page load, then smoothly animate it to the specified inline value. I prefer having the value inline so that our backend developers can easily integrate Ruby on Rails to output the desired percentage within the view. My initial approach includes implementing transitions as shown below:

CSS Implementation:

.chart .bar {
  -moz-transition: width 1.25s linear;
  -webkit-transition: width 1.25s linear;
  -ms-transition: width 1.25s linear;
  -o-transition: width 1.25s linear;
  transition: width 1.25s linear;
}

body.jquery.csstransitions:not(.loaded) .chart-container .chart .bar {
  width: 0% !important;
}

Utilizing JavaScript:

$(function() {
  $('body').addClass('jquery');

  // Further down in the script

  $('body').addClass('loaded');
});

This method relies on jQuery to add classes "jquery" and "csstransitions" only if JavaScript is enabled and CSS transitions are supported by the browser. However, there is a potential risk of bars displaying with 0% width if the script breaks before adding the "loaded" class. To address this issue, I am considering utilizing CSS keyframe animations to achieve the same effect without depending on JavaScript.

By incorporating CSS-based animations from 0% width to the designated value, I aim to eliminate the variable of JavaScript errors impacting the functionality of the charts. This approach ensures a more reliable performance by either animating the bars seamlessly or loading them statically sans animation effects.

Is there a technique available to animate/transition width during page load while minimizing reliance on JavaScript?

Answer №1

After exploring the concept of CSS keyframe animations, it turns out that understanding them wasn't as challenging as I initially thought. These animations essentially apply styles conditionally based on time and then transition smoothly between them. By omitting a style for a specific keyframe, the subsequent applied style seamlessly animates into place where the empty style would have been. This allows for creative possibilities like the following:

HTML:

<div class="chart">
  <div class="bar" style="width:43%;"></div>
</div>

CSS:

@-moz-keyframes animate-bar {
    0%   { width: 0%; }
}

@-webkit-keyframes animate-bar {
    0%   { width: 0%; }
}

@-ms-keyframes animate-bar {
    0%   { width: 0%; }
}

@-o-keyframes animate-bar {
    0%   { width: 0%; }
}

@-keyframes animate-bar {
    0%   { width: 0%; }
}

.chart {
  background-color: #DADADA;
  height: 2px;
  position: relative;
}

.chart .bar {
  background-color: #3D98C6;
  height: 100%;
  -moz-animation: animate-bar 1.25s 1 linear;
  -webkit-animation: animate-bar 1.25s 1 linear;
  -ms-animation: animate-bar 1.25s 1 linear;
  -o-animation: animate-bar 1.25s 1 linear;
  animation: animate-bar 1.25s 1 linear;
}

This approach allows the initial animation percentage of 0% to smoothly transition to the inline style specified, showcasing how the absence of a finishing style results in the next applicable style taking precedence.

Edit:

To provide further clarity, I've assembled a JS Fiddle example for reference purposes.

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 loading of content will happen only after the fadeOut effect

I'm attempting to incorporate content loading between fadeOut and fadeIn. When I execute the code below, the content loads before the fadeOut is complete: $("#contentArea").fadeOut(1000); $("#contentArea").promise().done(); $("#contentArea").load(c ...

Positioning the sDom in jQuery DataTables

Take a look at the image below: I want to adjust the position of the tableTools buttons (Copy, Excel, CSV) so that they appear aligned with the Search Box. I've experimented with different sDom parameters but haven't been successful. This is th ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

When attempting to submit, the jQuery validations fail to function accordingly

I have created an HTML form along with jQuery for validation purposes. However, upon clicking the submit button, nothing seems to be happening. I am unsure if my form is properly connecting with the jQuery file or not. Can someone please review my code and ...

What is the best way to center a div vertically on the page?

I've utilized Bootstrap 3 to create this row: <div class="cart"> <div class="row border"> <div class="col-md-8 desc pad itemsheight"> <div class="col-md-12"> <!-- react-text: 141 -->Docos <!-- /react ...

Enhance the visual appeal of your website by incorporating a loading animation into your jQuery AJAX

Here is the code I currently have, which is quite straightforward: $('#window').load('http://mysite.com/mypage.php'); However, the content is only displayed after it has fully loaded, leaving the #windows element empty during that tim ...

Converting units to rem dynamically in CSS: a comprehensive guide

Hey there, I'm currently trying to dynamically convert units into rem in CSS and facing some issues. I have set the root font-size as 23px The current font-size is 16px The expected result should be 16 / 23 => 0.695rem Question: I am looking for ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

Footer that sticks to the bottom of the page across various pages

Having trouble printing a 2-page document on Chrome. The first page has fixed content while the second page has dynamic content in an extended table. The problem I'm facing is keeping the footer at the bottom of the second page. The CSS code below wo ...

Retrieving data from a <div> element within an HTML string using jQuery and AJAX

Having trouble extracting a value from a div within an HTML string. Seeking assistance in identifying the issue. I've attempted various methods to retrieve the data, but none seem to work for me. It appears I may be overlooking something crucial. $( ...

Identifying elements using xpath - Streamlined Xpath Techniques

I successfully found the element using the xpath copied directly from the code. Can someone assist me in creating a simpler xpath for the following code snippet, which is fully functional! WebElement oCheckbox = myDriver.findElement(By.xpath(".//*[@id=&ap ...

Having trouble getting the same styles to show up on .class::before and .class::after elements, even though I've applied them. The changes aren't reflecting on the live server

Currently, I am working on a project that involves an ordered list (ol), and I am trying to add pseudo elements (::before,::after) to enhance its appearance. Strangely, when I write ::before and ::after separately, the styles are applied and visible on the ...

Tips for properly removing Bootstrap 4 tooltips when deleting their corresponding DOM element using html()

In my Bootstrap 4 project, I've implemented a live search box that displays results with tooltips for longer descriptions. I've written jQuery scripts to hide the search results and their parent div when certain events occur, like clearing the se ...

What is the solution to prevent the div tag from being empty within Jquery UI Tabs?

I found this example that I am currently following: http://jqueryui.com/demos/tabs/#ajax After clicking on Tab1 and Tab2 in their example, the text disappears immediately, and the div box shrinks before new data is loaded. Is there a better way to handle ...

What are the steps to add border styles to the top and bottom rows in a tanstack expandable react table?

In my project, I am utilizing the combination of Material UI and React Table. Recently, I was asked to add an expandable row, and I successfully implemented that feature. Once a user expands the row, we display additional table rows based on the data. If ...

Slippery carousel: Showcase all items in center alignment mode

Currently, I am implementing Slick Carousel with centerMode. Is there a method to ensure that all items are displayed without being cut off on the screen? The setup I have is quite simple: $('.your-class').slick({ centerMode: true, slidesTo ...

Popup mode is utilized by CodeIgniter error pages to display error messages

Is there a way to show error messages without being redirected to the error pages located in application\errors\*error_pages*? We want to remain on the same page and display any errors that occur in a popup. Can someone provide an example code fo ...

Prevent elements from collapsing within the Bootstrap 5 grid system

Hey there, happy Friday everyone! I've been working on rebuilding my company's website to learn HTML and CSS. I'm currently creating a replica of the original site and it's going really well so far. However, I've run into some is ...

Having trouble getting your Raspberry Pi web server to display the background image?

Recently, I successfully set up a LAMP server on my raspberrypi which was quite exciting. One of the first things I did was configure an FTP server to transfer webpage files to the Pi. I managed to create a basic form of the final webpage and transferred i ...

Is the whitespace-pre-line feature of TailwindCSS experiencing issues?

whitespace-pre-line doesn't seem to be working for me. I attempted to replicate the same code from my text editor on https://play.tailwindcss.com/, and it worked perfectly. Below is a screenshot that I have attached. This is the sample code in my tex ...