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

Firefox showing inconsistent jQuery positioning results

Here is a fiddle I created to demonstrate the issue at hand... https://jsfiddle.net/scottieslg/q78afsu8/10/ Running this fiddle in Chrome or Opera yields a value of 8. However, Firefox returns 9, and IE gives 8.5. How can I ensure consistency across al ...

Display a list next to a block of text and image using HTML and CSS styling

I am having trouble with keeping a navigation list aligned inline with a block of text that includes an image. My issue arises when I expand the browser to full screen size, causing the list to overlap the text block. Here is the HTML code snippet: <bo ...

Steps for properly inserting a hyperlink:

I'm in need of assistance. I have a grid containing several images that I want to make clickable by adding anchor tags, but when I do this, the images seem to disappear completely. I suspect there's an issue with them being inside the container d ...

Trigger a jQuery event when a different selection is made in the dropdown menu

There are 2 choices available in the dropdown menu. <select id="_fid_140" onchange="chooseRecordPicker()" > <option value="736">9000000146</option> <option value="x3recpcker#">&lt; Browse choices... &gt;</option> Upo ...

Create a stylish navigation dropdown with MaterializeCSS

Incorporating the materializecss dropdown menu feature, I encountered an issue where only two out of four dropdown menu items were visible. Here is the HTML code snippet in question: <nav class="white blue-text"> <div class="navbar-wrapper con ...

Inserting a border both above and below an element may result in the parent overflowing

I am facing an issue similar to the following: div.parent { height: 100px; padding: 20px; box-sizing: border-box; overflow: auto; } div.parent div.thing { height: 20px; width: 90%; border: 1px solid black; } <div class="parent"> ...

Creating a single Vuetify expansion panel: A step-by-step guide

Is there a way to modify the Vuetify expansion panel so that only one panel can be open at a time? Currently, all panels can be closed which is causing issues. I would like the last opened panel to remain open. I also want to prevent closing the currently ...

Combining jQuery methods and selectors within a loop

Can a sequence of selectors and methods be generated within a loop? For instance, assuming an array of elements is given: array[0] = '.type1value1, .type1value2, .type1value3'; array[1] = '.type2value1, .type2value2, .type2value3'; ar ...

Transforming a collection of items into a JSON format string

UPDATE: There was a mistake in the programming, please refrain from submitting answers. This question will be removed. If you have already submitted an answer, kindly delete it. I am attempting to submit a form using jQuery and ajax. One of the fields con ...

Performing automatic submission of form data without needing to redirect or refresh the page using Javascript

I am trying to find a way to automatically submit form post data without the page redirecting, but I haven't had success with any of the examples I've found that involve jquery and ajax. Currently, my code redirects the page: <!DOCTYPE html& ...

Linking states using AngularJS and jQuery

Imagine I have a scenario with two different states: .state('page1', { url: '/page1', templateUrl: 'pages/templates/page1.html', controller: 'page1' }) .state('page2', { url: '/page2& ...

"Enhance your website design with a navbar that seamlessly blends with the background color

Question 1: I have a requirement for my navbar to affix overlay on top of the background color and image of the div (top-banner). Currently, when I scroll down, the background color overlays my navbar affix instead. How can I ensure that my navbar sta ...

Is there a way to modify the spacing between labels and text in the TextBox MUI component while using custom label sizes?

I've customized a material ui TextField component by increasing the font size of the label. However, I'm facing an issue where the gap in the border for the label remains unchanged despite the larger text size. I couldn't find any solution ...

What causes the position: sticky; property to fail in React implementations?

Currently, I am facing a challenge in making two sidebars sticky so that they will follow as the user scrolls until they reach the bottom of the page. In my current editing project, this implementation seems to be more complex compared to other programs w ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

What is the method for eliminating PHP $_SESSION using AJAX?

I am facing an issue with removing an array within a PHP Session variable using AJAX. Here is the process I follow: HTML: <a href="#" onclick="delete_pix(false, '1', false, '1.jpg');">remove</a> JavaScript: functio ...

Leverage jQuery to Retrieve Text and Modify

My Content Management System automatically generates a time stamp for when a page was last updated. However, the format it provides is not ideal for my needs. I would like the date to be displayed in the US Standard way - May 24, 2013, without including th ...

A JavaScript String Utilizing an HTML Document

When developing applications for my website using JQuery, I encountered an issue with pulling an html document into a string. I want the application button to open a window with the html document inside. I am attempting to modify this string variable with ...

Ways to recognize when a button has been pressed

I developed my website using the CodeIgniter framework. Here is my personal website On the homepage, if I click on the "landscape" picture (top right) or the "landscape" button in the menu, it takes me to the "landscape" page. However, when I return to t ...

Styling a list using multiple columns with CSS

My goal is to design a columned list using only HTML and CSS. I have experimented with floats and inline-block, but it seems like inline-block is the best option for me due to these specific requirements: The layout must be in columns; The number of colu ...