1. Web Design
  2. UX/UI
  3. Responsive Design

Building a Horizontal Timeline With CSS and JavaScript

Scroll to top

In a previous post, I showed you how to build a responsive vertical timeline from scratch. Today, I’ll cover the process of creating the associated horizontal timeline.

What We’re Creating

As usual, to get an initial idea of what we’ll be building, take a look at the related CodePen demo (check out the larger version for a better experience):

This tutorial has been updated with another timeline version—check out the demo below and the added extra section!

We have a lot to cover, so let’s get started!

1. HTML Markup

The markup is identical to the markup we defined for the vertical timeline, apart from three small things:

  • We use an ordered list instead of an unordered list as that’s more semantically correct.
  • There’s an extra list item (the last one) that is empty. In an upcoming section, we’ll discuss the reason.
  • There’s an extra element (i.e. .arrows) that is responsible for the timeline navigation.

Here’s the required markup:

1
<section class="timeline">
2
  <ol>
3
    <li>
4
      <div>
5
        <time>1934</time>
6
        Some content here
7
      </div>
8
    </li>
9
     
10
    <!-- more list items here -->
11
    
12
    <li></li>
13
  </ol>
14
  
15
  <div class="arrows">
16
    <button class="arrow arrow__prev disabled" disabled>
17
      <img src="arrow_prev.svg" alt="prev timeline arrow">
18
    </button>
19
    <button class="arrow arrow__next">
20
      <img src="arrow_next.svg" alt="next timeline arrow">
21
    </button>
22
  </div>
23
</section>

The initial state of the timeline looks like this:

2. Adding Initial CSS Styles

After some basic font styles, color styles, etc. which I’ve omitted here for the sake of simplicity, we specify some structural CSS rules:

1
.timeline {
2
  white-space: nowrap;
3
  overflow-x: hidden;
4
}
5
6
.timeline ol {
7
  font-size: 0;
8
  width: 100vw;
9
  padding: 250px 0;
10
  transition: all 1s;
11
}
12
13
.timeline ol li {
14
  position: relative;
15
  display: inline-block;
16
  list-style-type: none;
17
  width: 160px;
18
  height: 3px;
19
  background: #fff;
20
}
21
22
.timeline ol li:last-child {
23
  width: 280px;
24
}
25
26
.timeline ol li:not(:first-child) {
27
  margin-left: 14px;
28
}
29
30
.timeline ol li:not(:last-child)::after {
31
  content: '';
32
  position: absolute;
33
  top: 50%;
34
  left: calc(100% + 1px);
35
  bottom: 0;
36
  width: 12px;
37
  height: 12px;
38
  transform: translateY(-50%);
39
  border-radius: 50%;
40
  background: #F45B69;
41
}

Most importantly here, you’ll notice two things:

  • We assign large top and bottom paddings to the list. Again, we’ll explain why that happens in the next section. 
  • As you’ll notice in the following demo, at this point, we cannot see all the list items because the list has width: 100vw and its parent has overflow-x: hidden. This effectively “masks” the list items. Thanks to the timeline navigation, however, we’ll be able to navigate through the items later.

With these rules in place, here’s the current state of the timeline (without any actual content, to keep things clear):

3. Timeline Element Styles

At this point we’ll style the div elements (we’ll call them “timeline elements” from now on) which are part of the list items as well as their ::before pseudo-elements.

Additionally, we’ll use the :nth-child(odd) and :nth-child(even) CSS pseudo-classes to differentiate the styles for the odd and even divs.

Here are the common styles for the timeline elements:

1
.timeline ol li div {
2
  position: absolute;
3
  left: calc(100% + 7px);
4
  width: 280px;
5
  padding: 15px;
6
  font-size: 1rem;
7
  white-space: normal;
8
  color: black;
9
  background: white;
10
}
11
12
.timeline ol li div::before {
13
  content: '';
14
  position: absolute;
15
  top: 100%;
16
  left: 0;
17
  width: 0;
18
  height: 0;
19
  border-style: solid;
20
}

Then some styles for the odd ones:

1
.timeline ol li:nth-child(odd) div {
2
  top: -16px;
3
  transform: translateY(-100%);
4
}
5
6
.timeline ol li:nth-child(odd) div::before {
7
  top: 100%;
8
  border-width: 8px 8px 0 0;
9
  border-color: white transparent transparent transparent;
10
}

And finally some styles for the even ones:

1
.timeline ol li:nth-child(even) div {
2
  top: calc(100% + 16px);
3
}
4
5
.timeline ol li:nth-child(even) div::before {
6
  top: -8px;
7
  border-width: 8px 0 0 8px;
8
  border-color: transparent transparent transparent white;
9
}

Here’s the new state of the timeline, with content added again:

As you’ve probably noticed, the timeline elements are absolutely positioned. That means they are removed from the normal document flow. With that in mind, in order to ensure that the whole timeline appears, we have to set large top and bottom padding values for the list. If we don’t apply any paddings, the timeline will be cropped:

How the timeline looks like without paddingsHow the timeline looks like without paddingsHow the timeline looks like without paddings

4. Timeline Navigation Styles

It’s now time to style the navigation buttons. Remember that by default we disable the previous arrow and give it the class of disabled.

Here are the associated CSS styles:

1
.timeline .arrows {
2
  display: flex;
3
  justify-content: center;
4
  margin-bottom: 20px;
5
}
6
7
.timeline .arrows .arrow__prev {
8
  margin-right: 20px;
9
}
10
11
.timeline .disabled {
12
  opacity: .5;
13
}
14
15
.timeline .arrows img {
16
  width: 45px;
17
  height: 45px;
18
}

The rules above give us this timeline:

5. Adding Interactivity

The basic structure of the timeline is ready. Let’s add some interactivity to it!

Variables

First things first, we set up a bunch of variables that we’ll use later. 

1
const timeline = document.querySelector(".timeline ol"),
2
  elH = document.querySelectorAll(".timeline li > div"),
3
  arrows = document.querySelectorAll(".timeline .arrows .arrow"),
4
  arrowPrev = document.querySelector(".timeline .arrows .arrow__prev"),
5
  arrowNext = document.querySelector(".timeline .arrows .arrow__next"),
6
  firstItem = document.querySelector(".timeline li:first-child"),
7
  lastItem = document.querySelector(".timeline li:last-child"),
8
  xScrolling = 280,
9
  disabledClass = "disabled";

Initializing Things

When all page assets are ready, the init function is called.

1
window.addEventListener("load", init);

This function triggers four sub-functions:

1
function init() {
2
  setEqualHeights(elH);
3
  animateTl(xScrolling, arrows, timeline);
4
  setSwipeFn(timeline, arrowPrev, arrowNext);
5
  setKeyboardFn(arrowPrev, arrowNext);
6
}

As we’ll see in a moment, each of these functions accomplishes a certain task.

Equal-Height Timeline Elements

If you jump back to the last demo, you’ll notice that the timeline elements don’t have equal heights. This doesn’t affect the main functionality of our timeline, but you might prefer it if all elements had the same height. To achieve this, we can give them either a fixed height via CSS (easy solution) or a dynamic height that corresponds to the height of the tallest element via JavaScript.

The second option is more flexible and stable, so here’s a function that implements this behavior:

1
function setEqualHeights(el) {
2
  let counter = 0;
3
  for (let i = 0; i < el.length; i++) {
4
    const singleHeight = el[i].offsetHeight;
5
    
6
    if (counter < singleHeight) {
7
      counter = singleHeight;
8
    }
9
  }
10
  
11
  for (let i = 0; i < el.length; i++) {
12
    el[i].style.height = `${counter}px`;
13
  }
14
}

This function retrieves the height of the tallest timeline element and sets it as the default height for all the elements.

Here’s how the demo’s looking:

6. Animating the Timeline

Now let’s focus on the timeline animation. We’ll build the function that implements this behavior step-by-step.

First, we register a click event listener for the timeline buttons:

1
function animateTl(scrolling, el, tl) {
2
  for (let i = 0; i < el.length; i++) {
3
    el[i].addEventListener("click", function() {
4
      // code here

5
    });
6
  }
7
}

Each time a button is clicked, we check the disabled state of the timeline buttons, and if they aren’t disabled, we disable them. This ensures that both buttons will be clicked only once until the animation finishes.

So, in terms of code, the click handler initially contains these lines:

1
if (!arrowPrev.disabled) {
2
  arrowPrev.disabled = true;
3
}
4
5
if (!arrowNext.disabled) {
6
  arrowNext.disabled = true;
7
}

The next steps are as follows:

  • We check to see if it’s the first time we’ve clicked on a button. Again, keep in mind that the previous button is disabled by default, so the only button that can be clicked initially is the next one.
  • If indeed it’s the first time, we use the transform property to move the timeline 280px to the right. The value of the xScrolling variable determines the amount of movement. 
  • On the contrary, if we’ve already clicked on a button, we retrieve the current transform value of the timeline and add or remove to that value, the desired amount of movement (i.e. 280px). So, as long as we click on the previous button, the value of the transform property decreases and the timeline is moved from left to right. However, when the next button is clicked, the value of the transform property increases, and the timeline is moved from right to left.

The code that implements this functionality is as follows:

1
let counter = 0; 
2
for (let i = 0; i < el.length; i++) {
3
  el[i].addEventListener("click", function() {
4
    // other code here

5
  
6
    const sign = (this.classList.contains("arrow__prev")) ? "" : "-";
7
    if (counter === 0) {
8
      tl.style.transform = `translateX(-${scrolling}px)`;
9
    } else {
10
      const tlStyle = getComputedStyle(tl);
11
      // add more browser prefixes if needed here

12
      const tlTransform = tlStyle.getPropertyValue("-webkit-transform") || tlStyle.getPropertyValue("transform");
13
      const values = parseInt(tlTransform.split(",")[4]) + parseInt(`${sign}${scrolling}`);
14
      tl.style.transform = `translateX(${values}px)`;
15
    }
16
    counter++;
17
  });
18
}

Great job! We’ve just defined a way of animating the timeline. The next challenge is to figure out when this animation should stop. Here’s our approach:

  • When the first timeline element becomes fully visible, it means that we’ve already reached the beginning of the timeline, and thus we disable the previous button. We also ensure that the next button is enabled.
  • When the last element becomes fully visible, it means that we’ve already reached the end of the timeline, and thus we disable the next button. We also, therefore, ensure that the previous button is enabled.

Remember that the last element is an empty one with a width equal to the width of the timeline elements (i.e. 280px). We give it this value (or a higher one) because we want to make sure that the last timeline element will be visible before disabling the next button.

To detect whether the target elements are fully visible in the current viewport or not, we’ll take advantage of the same code we used for the vertical timeline. The required code which comes from this Stack Overflow thread is as follows:

1
function isElementInViewport(el) {
2
  const rect = el.getBoundingClientRect();
3
  return (
4
    rect.top >= 0 &&
5
    rect.left >= 0 &&
6
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
7
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
8
  );
9
}

Beyond the function above, we define another helper:

1
function setBtnState(el, flag = true) {
2
  if (flag) {
3
    el.classList.add(disabledClass);
4
  } else {
5
    if (el.classList.contains(disabledClass)) {
6
      el.classList.remove(disabledClass);
7
    }
8
    el.disabled = false;
9
  }
10
}

This function adds or removes the disabled class from an element based on the value of the flag parameter. In addition, it can change the disabled state for this element.

Given what we’ve described above, here’s the code we define for checking whether the animation should stop or not:

1
for (let i = 0; i < el.length; i++) {
2
  el[i].addEventListener("click", function() {
3
    // other code here

4
    
5
    // code for stopping the animation

6
    setTimeout(() => {
7
      isElementInViewport(firstItem) ? setBtnState(arrowPrev) : setBtnState(arrowPrev, false);
8
      isElementInViewport(lastItem) ? setBtnState(arrowNext) : setBtnState(arrowNext, false);
9
    }, 1100);
10
  
11
    // other code here

12
  });
13
}

Notice that there’s a 1.1 second delay before executing this code. Why does this happen?

If we go back to our CSS, we’ll see this rule:

1
.timeline ol {
2
  transition: all 1s;
3
}

So, the timeline animation needs 1 second to complete. As long as it completes, we wait for 100 milliseconds and then, we perform our checks.

Here’s the timeline with animations:

7. Adding Swipe Support

So far, the timeline doesn’t respond to touch events. It would be nice if we could add this functionality, though. To accomplish it, we can write our own JavaScript implementation or use one of the related libraries (e.g. Hammer.js, TouchSwipe.js) that exist out there.

For our demo, we’ll keep this simple and use Hammer.js, so first, we include this library in our pen:

How to include Hammerjs in our penHow to include Hammerjs in our penHow to include Hammerjs in our pen

Then we declare the associated function:

1
function setSwipeFn(tl, prev, next) {
2
  const hammer = new Hammer(tl);
3
  hammer.on("swipeleft", () => next.click());
4
  hammer.on("swiperight", () => prev.click());
5
}

Inside the function above, we do the following:

  • Create an instance of Hammer. 
  • Register handlers for the swipeleft and swiperight events. 
  • When we swipe over the timeline in the left direction, we trigger a click to the next button, and thus the timeline is animated from right to left.
  • When we swipe over the timeline in the right direction, we trigger a click to the previous button, and thus the timeline is animated from left to right.

The timeline with swipe support:

8. Adding Keyboard Navigation

Let’s further enhance the user experience by providing support for keyboard navigation. Our goals:

  • When the left or right arrow key is pressed, the document should be scrolled to the top position of the timeline (if another page section is currently visible). This ensures that the whole timeline will be visible.
  • Specifically, when the left arrow key is pressed, the timeline should be animated from left to right.
  • In the same way, when the right arrow key is pressed, the timeline should be animated from right to left.

The associated function is the following:

1
function setKeyboardFn(prev, next) {
2
  document.addEventListener("keydown", (e) => {
3
    if ((e.which === 37) || (e.which === 39)) {
4
      const timelineOfTop = timeline.offsetTop;
5
      const y = window.pageYOffset;
6
      if (timelineOfTop !== y) {
7
        window.scrollTo(0, timelineOfTop);
8
      } 
9
      if (e.which === 37) {
10
        prev.click();
11
      } else if (e.which === 39) {
12
        next.click();
13
      }
14
    }
15
  });
16
}

The timeline with keyboard support:

9. Going Responsive

We’re almost done! Last but not least, let’s make the timeline responsive. When the viewport is less than 600px, it should have the following stacked layout:

As we’re using a desktop-first approach, here are the CSS rules that we have to overwrite:

1
@media screen and (max-width: 599px) {
2
  .timeline ol,
3
  .timeline ol li {
4
    width: auto; 
5
  }
6
  
7
  .timeline ol {
8
    padding: 0;
9
    transform: none !important;
10
  }
11
  
12
  .timeline ol li {
13
    display: block;
14
    height: auto;
15
    background: transparent;
16
  }
17
  
18
  .timeline ol li:first-child {
19
    margin-top: 25px;
20
  }
21
  
22
  .timeline ol li:not(:first-child) {
23
    margin-left: auto;
24
  }
25
  
26
  .timeline ol li div {
27
    position: static;
28
    width: 94%;
29
    height: auto !important;
30
    margin: 0 auto 25px;
31
  }
32
  
33
  .timeline ol li:nth-child(odd) div {
34
    transform: none;
35
  }
36
  
37
  .timeline ol li:nth-child(odd) div::before,
38
  .timeline ol li:nth-child(even) div::before {
39
    left: 50%;
40
    top: 100%;
41
    transform: translateX(-50%);
42
    border: none;
43
    border-left: 1px solid white;
44
    height: 25px;
45
  }
46
  
47
  .timeline ol li:last-child,
48
  .timeline ol li:nth-last-child(2) div::before,
49
  .timeline ol li:not(:last-child)::after,
50
  .timeline .arrows {
51
    display: none;
52
  }
53
}
For two of the rules above, we had to use the !important rule to override the related inline styles applied through JavaScript. 

The final state of our timeline:

Browser Support

The demo works well in all recent browsers and devices. Also, as you’ve possibly noticed, we use Babel to compile our ES6 code down to ES5.

The only small issue I encountered while testing it is the text rendering change that happens when the timeline is being animated. Although I tried various approaches proposed in different Stack Overflow threads, I didn’t find a straightforward solution for all operating systems and browsers. So, keep in your mind that you might see small font rendering issues as the timeline is being animated.

EXTRA: Timeline v2

Let’s now build an alternative timeline variation where a custom scrollbar is used for the navigation.

Before starting, it’s worth mentioning two things:

  • Timeline aesthetics are based on a template that provides a collection of UI components and is available on Envato Elements.
UI template from Envato ElementsUI template from Envato ElementsUI template from Envato Elements
Finance - UI Components on Envato Elements

Below you can see the timeline layout across various screens. The concept remains the same; we don’t reposition elements as with the previous timeline. The only difference occurs on large screens where we show an additional section that describes in more detail the timeline (company history).

The mobile layout of the horizontal timelineThe mobile layout of the horizontal timelineThe mobile layout of the horizontal timeline
The layout on mobile screens (<801px)
The desktop layout of the horizontal timelineThe desktop layout of the horizontal timelineThe desktop layout of the horizontal timeline
The layout on desktop screens

Concerning the development, let’s highlight the key aspects:

  • On the timeline edges, we set two gradients that help disguise its boundaries. You can see it clearly by looking again at the visualizations above.
  • We don’t need so much JavaScript for this implementation. We’ll only keep the required function for accomplishing equal heights to the timeline elements. 
  • We use CSS scroll snapping to prevent over-scrolling and allow users to lock (snap) to specific scroll points. Feel free to remove it if you aren’t a big fan of this feature.

Here’s our timeline—for a better experience, be sure to view it from a large screen:

Conclusion

In this fairly substantial tutorial, we started with a simple ordered list and created a responsive horizontal timeline. But we didn’t stop here; we also went through an alternative implementation with a scrolling timeline UI. We covered a lot of interesting things! I hope you enjoyed working toward the final result and that it helped you gain some new knowledge.

If you have any questions or if there’s anything you didn’t understand, let us know on Twitter or in the CodePen demos’ comments!

Next Steps

If you want to further improve or extend this timeline, here are a few things you can do:

  • Add support for dragging. Instead of clicking the timeline buttons for navigating, we could just drag the timeline area. For this behavior, you could use either the native Drag and Drop API (which has substantial browser support at the time of writing) or an external library like Draggable.js.
  • Improve the timeline behavior as we resize the browser window. For instance, as we resize the window, the buttons should be enabled and disabled accordingly.
  • Organize the code in a more manageable way. Perhaps, use a common JavaScript Design Pattern.

As always, thanks a lot for reading!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.