Yogesh Chauhan's Blog

How to animate list items using CSS and JavaScript?

in CSS & JavaScript on February 14, 2021

In this post, I demonstrated how to add and remove list items. There was no style or animation in list items.

Let’s add some style to the list items.


li {
  list-style: none;
  background: navy;
  color: #fff;
  line-height: 2;
  padding: 0 2%;
  overflow: hidden;
  width: 10%;
  text-align: center;
  border-radius: 10px;
  margin: 2px 0;
}

This is how it will look like afterwards:

Fading Animation

To create a fading animation, we can make use of opacity and transition property.

Also, we need to add additional class to inject using script.


li {
  ...
  transition: all 0.4s ease-out;
  opacity: 0;
  ...
}
li.show {
  opacity: 1;
}

Finally, in JavaScript, we need to inject the show class we created in CSS but after few microseconds. We can do that using setTimeout.


...
  setTimeout(function() {
    newEl.className = newEl.className + " fade show";
  }, 10);
...

Checkout the animation in action:

Sliding Down

Sliding down animation is all about height. We’re going to set the height to 0 initially. We’ll have height set in show class so when we inject the show class the height will go from 0 to 30px.

Here is the demo in action:


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What is ECMAScript?JavaScript@mixin and @include in SCSS (Sass)SCSSWordPress get_posts ExamplesWordPressHow to send and receive query strings via links in Angular 9?AngularDROP DATABASE (remove a database) from PostgresPostgresHigher Order Functions in JavaScript with ExamplesJavaScriptIntroduction to components and templates Part 1: Component MetadataAngularHow to get query string values in JavaScript? (URL Manipulation using URLSearchParams)JavaScriptHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresWhat are Null Sessions?MiscellaneousWhere is the PHP log file located on Mac OS?PHPHow to set up the local environment and workspace for Angular development?Angular