Timelines are powerful visual tools that help users navigate and understand chronological events. Explore how to create an interactive timeline using the dynamic duo of CSS and JavaScript.

Building the Timeline Structure

you’re able to check out the full code for this project from itsGitHub repository.

To begin, outline the HTML structure inindex.html. Create events and dates as separate components, laying the foundation for the interactive timeline.

Timeline component html structure

At the moment, your component looks like this:

Pick a Layout for Your Timeline: Vertical vs. Horizontal

When designing an interactive timeline, you can choose either a vertical or horizontal style. Vertical timelines are easy to use, especially on phones, as this is the typical direction that websites scroll in. If your timeline has a lot of content, this will probably be the most convenient layout.

Horizontal timelines, however, are appealing on wide screens and are great for creative sites with fewer details, that can minimize side-to-side scrolling. Each style has its perks, suitable for different types of websites and user experiences.

Timeline component after styling

Style the Timeline With CSS

There are three types of visual elements you’ll style for the timeline: lines, nodes, and date markers.

Check out the full set of styles from theGitHub repo instyle.css.

After styling, your component should look like this:

Animating With JavaScript

To animate this component, usethe Intersection Observer APIto animate timeline items on scroll. Add the following code toscript.js.

1. Initial Setup

First, select all elements with the class Timeline__item.

2. Initial Styling of Timeline Items

Set the initial opacity of each item to 0 (invisible) and apply aCSS transition for smooth fading.

You could set these styles in the style sheet, but doing so would be dangerous. If the JavaScript fails to run, that approach would leave your timeline invisible! Isolating this behavior in the JavaScript file is a good example ofprogressive enhancement.

3. Intersection Observer Callback

Define a fadeInOnScroll function to change the opacity of items to 1 (visible) when they intersect with the viewport.

4. Intersection Observer Options

Set the options for the observer, with a threshold of 0.1 indicating that the animation triggers when 10% of an item is visible.

5. Creating and Using the Intersection Observer

Finish by creating an IntersectionObserver with these options and applying it to each timeline item.

The final result should look like this:

Timeline Component Best Practices

Some practices to adhere to include:

Bringing Your Timeline to Life: A Journey in Web Design

Building an interactive timeline is not just about presenting information; it’s about creating an engaging and informative experience. By combining HTML structure, CSS styling, and JavaScript animations, you can craft a timeline that captivates your audience while delivering valuable content.