Simple Tabs With AJAX Pure Javascript (Free Download)

Welcome to a tutorial on how to create responsive tabs with Javascript and CSS. There sure are a lot of “tab plugins” on the Internet, but how do we create one that loads content with AJAX? Here is a quick sharing of my version, without any dependencies on third-party frameworks. Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Notes How It Works Useful Bits & Links
The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

HOW TO USE

tabs.html
<!-- (A) LOAD CSS + JS -->
<link href="tabs.css" rel="stylesheet">
<script src="tabs.js"></script>
 
<!-- (B) TABS WRAPPER -->
<div id="myTabs">
  <a href="1-first.html">First</a>
  <a href="2-second.html">Second</a>
  <a href="3-third.html">Third</a>
</div>

<!-- (C) INIT TABS -->
<script>
atabify("myTabs");
</script> 

For you guys who just want to use this as a “plugin”:

  1. Load the CSS and Javascript. Doh.
  2. Just define all the tabs headers as <a href="URL">, wrap them in a <div>.
  3. Lastly, just call atabify(TARGET) to create the tab.

 

 

HOW IT WORKS

All right, let us now walk through how the Javascript tab works in more detail.

 

THE JAVASCRIPT

tabs.js
function atabify (target) {
  // (A) GET TARGET & TABS
  let header = document.getElementById(target),
      tabs = header.getElementsByTagName("a");
 
  // (B) CREATE TAB HTML
  // (B1) WRAPPER
  let wrapper = document.createElement("div");
  wrapper.className = "tabWrap";
  header.before(wrapper);
 
  // (B2) HEADER
  wrapper.appendChild(header);
  header.classList.add("tabHead");
 
  // (B3) CONTENT
  let body = document.createElement("div");
  body.className = "tabBody";
  wrapper.appendChild(body);
 
  // (C) ATTACH CLICK TO AJAX LOAD
  for (let i of tabs) {
    let url = i.href;
    i.removeAttribute("href");
    i.onclick = () => {
      fetch(url).then(res => res.text())
      .then(txt => {
        for (let j of tabs) {
          if (j==i) { j.classList.add("open"); }
          else { j.classList.remove("open"); }
        }
        body.innerHTML = txt;
      });
    };
  }
 
  // (D) LOAD DEFAULT TAB - FIRST BY DEFAULT
  let open = header.querySelector(".open");
  if (open==null) { open = tabs[0]; }
  open.click();
}

The entire tabs mechanism is contained within this atabify() function. Looks complicated, but keep calm and look carefully.

  1. Get the specified HTML <div> and all the <a> contained within.
  2. Creates the AJAX tab widget, see below for an example of the HTML that will be generated.
  3. “Convert” the href within the links to load via AJAX instead.
  4. Lastly, load the first tab by default.

 

 

TAB HTML

<div class="tabWrap">
  <!-- (A) HEADER - YOU DEFINED THIS PART -->
  <div id="myTabs" class="tabHead">
    <a class="open">First</a>
    <a>Second</a>
    <a>Third</a>
  </div>
 
  <!-- (B) CONTENT - LOADED VIA AJAX -->
  <div class="tabBody">
    <h1>FIRST</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </p>
  </div>
</div> 

This is how the HTML looks like after the setup is complete – We actually just wrapped the links in a <div class="tabWrap">, and added another <div class="tabBody"> to AJAX load the contents.

 

CSS COSMETICS

tabs.css
/* (A) WRAPPER */
.tabWrap, .tabWrap * {
  font-family: arial, sans-serif;
  box-sizing: border-box;
}
.tabWrap {
  max-width: 600px;
  margin: 0 auto;
  box-shadow: 5px 5px 10px -1px rgba(0,0,0,0.28);
}
 
/* (B) HEADER TABS */
.tabHead {
  display: flex;
  background: #efefef;
  padding: 0; margin: 0;
}
.tabHead a {
  padding: 10px 20px;
  /*flex-grow: 1; flex-basis: 0;*/
  cursor: pointer;
  text-decoration: none;
  color: #000;
}
.tabHead a.open {
  color: #fff;
  background: #2a87d7;
}

/* (C) CONTENT TAB */
.tabBody { padding: 20px; }

The CSS is just cosmetics… So, not really important, nothing functional here.

 

 

USEFUL BITS & LINKS

That’s all for the code, and here are a few small extras that may be useful to you.

 

SETTING DEFAULT OPEN TAB

<div id="myTabs">
  <a href="1-first.html">First</a>
  <a class="open" href="2-second.html">Second</a>
  <a href="3-third.html">Third</a>
</div>

As above, the first tab will be opened by default. If that is not the case, manually set a class="open" on both the respective <a>.

 

LINKS & REFERENCES

Looking for more ways to organize your content? Check out my other guides:

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better organize the information in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.