1. Web Design
  2. HTML/CSS
  3. Bootstrap

How to Add Deep Linking to the Bootstrap 4 Tabs Component

In this new tutorial we’ll learn how to add deep linking to the Bootstrap 4 tabs and make them shareable.
Scroll to top

Today we’ll learn how to add “deep linking” to the Bootstrap 4 tabs. To better understand what we’re working towards, check out the demo page and pay attention to two things:

  1. How the URL changes as you click on the tabs.
  2. By giving each of the tabs its own URL, the content becomes shareable. If you grab the URL of a tab and open it in another browser/window the corresponding tab will be visible.


Note that the URL reflects the selected tab

We’ll outline three main steps; the HTML, the CSS, and the JavaScript. A certain level of competency for all three of these is assumed. Excited to see how we’ll build this? If the answer is yes, let’s get started!

1. Building the Tabs

We’ll kick things off with a starter template taken from Bootstrap’s documentation.

1
<!doctype html>
2
<html lang="en">
3
  <head>
4
    <meta charset="utf-8">
5
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
7
    <!-- custom CSS -->
8
    <link rel="stylesheet" href="css/main.css">
9
    <title>How to Add Deep Linking to the Bootstrap 4 Tabs Component</title>
10
  </head>
11
  <body>
12
    <!-- content here -->
13
    
14
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
15
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
16
    <!-- custom JS -->
17
    <script src="js/main.js"></script>
18
  </body>
19
</html>

To create the tabs, we’ll take advantage of example code for the tab component that Bootstrap provides: 

1
<ul class="nav nav-mytabs" id="myTab" role="tablist">
2
  <li class="nav-item">
3
    <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
4
  </li>
5
  <li class="nav-item">
6
    <a class="nav-link" id="history-tab" data-toggle="tab" href="#history" role="tab" aria-controls="history" aria-selected="false">History</a>
7
  </li>
8
  <li class="nav-item">
9
    <a class="nav-link" id="city-attractions-tab" data-toggle="tab" href="#city-attractions" role="tab" aria-controls="city-attractions" aria-selected="false">City Attractions</a>
10
  </li>
11
</ul>
12
<div class="tab-content mytab-content" id="myTabContent">
13
  <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
14
    <!-- content here -->
15
  </div>
16
  <div class="tab-pane fade" id="history" role="tabpanel" aria-labelledby="history-tab">
17
    <!-- content here -->
18
  </div>
19
  <div class="tab-pane fade" id="city-attractions" role="tabpanel" aria-labelledby="city-attractions-tab">
20
    <!-- content here -->
21
  </div>
22
</div>

2. The CSS

Next we specify a few CSS rules for our component. Nothing too fancy, just some basic styles. It’s worth mentioning that in a previous tutorial, we used similar styles to build a custom tab component.

Here are the initial styles:

1
.nav-mytabs {
2
  margin-top: 2rem;
3
}
4
5
.nav-mytabs li:not(:last-child) {
6
  margin-right: 7px;
7
}
8
9
.nav-mytabs a {
10
  position: relative;
11
  top: 4px;
12
  padding: 10px 25px;
13
  border-radius: 2px 2px 0 0;
14
  background: white;
15
  color: black;
16
  opacity: 0.7;
17
  transition: all 0.1s ease-in-out;
18
}
19
20
.nav-mytabs a.active, 
21
.nav-mytabs a:hover {
22
  opacity: 1;
23
  top: 0;
24
}
25
26
.mytab-content {
27
  position: relative;
28
  z-index: 2;
29
  padding: 25px;
30
  border-radius: 0 4px 4px 4px;
31
  background: white;
32
}

3. The JavaScript

With the HTML and CSS in place, it’s time to look at the required JavaScript code (this is the important bit).

First, when the DOM is ready, we retrieve the page URL and use a regular expression to remove its trailing slash. For instance, if the original URL is something/, the modified URL will be something.

Next, we check to see if the URL contains a hash. If that is the case, it means we want to display the contents of the second or third tab (in our example). To do so, we carry out the following:

  1. Retrieve the name of the target tab and activate it by using Bootstrap’s tab method.
  2. Use a regular expression to generate the desired URL format.
  3. Update the page URL without forcing a page reload by taking advantage of the replaceState method.
  4. Optionally, force the page scroll to start from the top of the page.

Each time we click on a tab we do the following:

  1. Retrieve the href attribute value of this tab. In our case, the possible values are #home, #history, #city-attractions.
  2. Check the attribute value and, depending on that, build the desired URL format. 
  3. Update the page URL without forcing a page reload by taking advantage of the replaceState method.

Here’s the JavaScript which takes care of all that:

1
$(document).ready(() => {
2
  let url = location.href.replace(/\/$/, "");
3
4
  if (location.hash) {
5
    const hash = url.split("#");
6
    $('#myTab a[href="#'+hash[1]+'"]').tab("show");
7
    url = location.href.replace(/\/#/, "#");
8
    history.replaceState(null, null, url);
9
    setTimeout(() => {
10
      $(window).scrollTop(0);
11
    }, 400);
12
  } 
13
  
14
  $('a[data-toggle="tab"]').on("click", function() {
15
    let newUrl;
16
    const hash = $(this).attr("href");
17
    if(hash == "#home") {
18
      newUrl = url.split("#")[0];
19
    } else {
20
      newUrl = url.split("#")[0] + hash;
21
    }
22
    newUrl += "/";
23
    history.replaceState(null, null, newUrl);
24
  });
25
});

4. Browser Support

The demo should work well in all recent browsers. For simplicity, I haven’t used a JavaScript compiler (e.g. Babel), but in your own code you might have to.

Conclusion

In this tutorial, we managed to customize the behavior of the Bootstrap 4 tabs, by giving each tab an identifiable URL, making their content more navigable and shareable. Keep in mind that the process implemented here can also be applied to any other framework or even a custom tab component.

If there’s anything you didn’t understand, or anything seems unclear to you, let me know in the comments below!

Further Reading