HomeJavascriptHow To Create Tabs Using HTML, CSS And Javascript

How To Create Tabs Using HTML, CSS And Javascript

Hello everyone, welcome to yet another exciting tutorial. In today’s tutorial, we will learn how to create tabs. To build these tabs, we need HTML, CSS and Javascript.

The best way to gain valuable insights and hands-on-experience in web development such as Javascript is to enroll in technical training courses offered by reputated training consultants before diving into the complexities of creating tabs in Javascript. Tabs are navigation elements used to sort and display relatable information. This information usually comes in two parts. The first part is the tab title, and the second part is the tab description. Tabs allow users a quick go through the information by easy switching between information.

Video Tutorial:

If you would like to code along with me, you can check out the video version of this tutorial here down below. Also, I post a new video every alternate day. So do subscribe to my youtube channel to get access to these tutorials.

Project Folder Structure:

We start by creating the project folder structure. The project folder is – Tabs. Inside the project folder, we have three files. These files are index.html, style.css and script.js. They are the HTML document, the stylesheet and the script file respectively.

HTML:

We start to code the HTML first. Now copy the code below and paste it into your HTML file.

The HTML consists of a div with a class called container. Inside container, we have two divs with class – tabs and tab-content respectively. The tabs div comprises three h3 tags. One of these h3 tags has a class active.

The tab content consists of three div. Each of these divs has an h4 tag and a p tag. Even one of these tabs has an active class.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tabs</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="tabs">
        <h3 class="active">Tab 1</h3>
        <h3>Tab 2</h3>
        <h3>Tab 3</h3>
      </div>
      <div class="tab-content">
        <div class="active">
          <h4>First Title</h4>
          <p>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolore
            explicabo cum dolores hic possimus aut corrupti quisquam aperiam
            quia veniam inventore officiis nam error sunt libero, commodi
            architecto reiciendis qui fuga, itaque delectus quidem sequi.
            Impedit natus culpa nihil aperiam adipisci aliquam error, suscipit
            odio? Error sed esse perspiciatis quasi velit, ratione odit
            architecto? Explicabo pariatur.
          </p>
        </div>

        <div>
          <h4>Second Title</h4>
          <p>
            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Deleniti,
            fugiat ab? Accusamus sed a iusto? Placeat incidunt repudiandae vero
            magnam nihil tempore quasi earum illum totam aut delectus aliquam
            pariatur, iste, qui provident quo voluptatem neque facere id
            laudantium aliquid numquam nisi accusantium. Inventore reiciendis
            nulla, iste perferendis.
          </p>
        </div>

        <div>
          <h4>Third Title</h4>
          <p>
            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quaerat
            autem accusantium voluptate debitis ipsa animi aliquid dolore?
            Suscipit consequatur architecto ullam perferendis praesentium sed
            aliquid voluptatem quibusdam laborum, doloremque aut atque debitis
            et laudantium qui veniam eligendi accusamus ipsam optio, assumenda
            aliquam ipsum dolorem similique?
          </p>
        </div>
      </div>
    </div>
    <!--Script-->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Now to style these tabs, we use CSS. In the next step, do copy the code provided below and paste it into your stylesheet.

We start by removing paddings and margins from all the elements. Next, we set the background colour to #4d5bf9. We use transforms to centre the container.

If you are interested in technical training programs, you can check out the link here.

We use a grid layout to position out the tabs. Initially, we set the display of all the div’s inside tab-content. We use active class to set the content of tabs to back to block display. We add and remove this active class using javascript.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #4d5bf9;
}
.container {
  width: 80vmin;
  position: absolute;
  transform: translateX(-50%);
  left: 50%;
  top: 120px;
  background-color: #ffffff;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}
.tabs {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}
h3 {
  background-color: #e4e9fd;
  text-align: center;
  padding: 15px 0;
  cursor: pointer;
  font-weight: 600;
}
.tab-content {
  background-color: #ffffff;
  padding: 50px 40px;
}
.tab-content h4 {
  font-size: 28px;
  margin-bottom: 20px;
  color: #000224;
  font-weight: 600;
}
.tab-content p {
  text-align: justify;
  line-height: 1.9;
  letter-spacing: 0.4px;
  color: #202238;
}
.tab-content div {
  display: none;
}
.tab-content .active {
  display: block;
}
.tabs .active {
  background-color: #ffffff;
  color: #4d5bf9;
}

Javascript:

For the final step, we add functionality to these tabs with javascript. To add javascript to your code, copy the code below and paste it into your script file.

We first select the h3 elements inside tabs and div elements inside the tab-content. We assign them to two different variables. In the next step, we add a click event listener to each of these tabs. When a tab is clicked on, an active class is added to the corresponding tab content. At the same time, the active class is removed from any other tab content it was applied to.

let tabs = document.querySelectorAll(".tabs h3");
let tabContents = document.querySelectorAll(".tab-content div");

tabs.forEach((tab, index) => {
  tab.addEventListener("click", () => {
    tabContents.forEach((content) => {
      content.classList.remove("active");
    });
    tabs.forEach((tab) => {
      tab.classList.remove("active");
    });
    tabContents[index].classList.add("active");
    tabs[index].classList.add("active");
  });
});

Our tabs are now ready. If you have any issues while creating this code, download the source by clicking on the download button that is provided below. I would love to hear your ideas, suggestions and feedbacks. So do leave them in the comments below.

 

RELATED ARTICLES

2 COMMENTS

  1. Look, I was gonna go easy on you
    Not to hurt your feelings
    But I’m only going to get this one chance
    Something’s wrong, I can feel it
    (Six minutes)
    Just a feeling I’ve got
    Like something’s about to happen
    But I don’t know what
    If that means what I think it means
    We’re in trouble, big trouble
    And if he is as bananas as you say
    I’m not taking any chances
    You are just what the doc ordered
    I’m beginnin’ to feel like a Rap God, Rap God
    All my people from the front to the back nod, back nod
    Now, who thinks their arms are long enough
    To slap box, slap box?
    They said I rap like a robot, so call me Rap-bot
    But for me to rap like a computer
    It must be in my genes
    I got a laptop in my back pocket
    My pen’ll go off when I half-cock it
    Got a fat knot from that rap profit
    Made a livin’ and a killin’ off it
    Ever since Bill Clinton was still in office
    With Monica Lewinsky feelin’ on his nutsack
    I’m an MC still as honest
    But as rude and as indecent as all hell
    Syllables, skill-a-holic (Kill ’em all with)
    This flippity dippity-hippity hip-hop
    You don’t really wanna get into a pissin’ match
    With this rappity brat, packin’ a MAC
    In the back of the Ac’
    Backpack rap crap, yap-yap, yackety-yack
    And at the exact same time
    I attempt these lyrical acrobat stunts
    While I’m practicin’ that
    I’ll still be able to break a motherfuckin’ table
    Over the back of a couple of faggots and crack it in half
    Only realized it was ironic
    I was signed to Aftermath after the fact
    How could I not blow?
    All I do is drop F-bombs
    Feel my wrath of attack
    Rappers are havin’ a rough time period
    Here’s a maxi pad
    It’s actually disastrously bad for the wack
    While I’m masterfully constructing this masterpiece as
    ‘Cause I’m beginnin’ to feel like a Rap God, Rap God
    All my people from the front to the back nod, back nod
    Now, who thinks their arms are long enough to slap box, slap box?
    Let me show you maintainin’ this shit ain’t that hard, that hard
    Everybody wants the key and the secret
    To rap immortality like Ι have got
    Well, to be truthful the blueprint’s
    Simply rage and youthful exuberance
    Everybody loves to root for a nuisance
    Hit the Earth like an asteroid
    Did nothing but shoot for the Moon since (Pew!)
    MCs get taken to school with this music
    ‘Cause I use it as a vehicle to “bus the rhyme”
    Now I lead a new school full of students
    Me? I’m a product of Rakim
    Lakim Shabazz, 2Pac, N.W.A, Cube, hey Doc, Ren
    Yella, Eazy, thank you, they got Slim
    Inspired enough to one day grow up
    Blow up and be in a position
    To meet Run–D.M.C., induct them
    Into the motherfuckin’ Rock and Roll Hall of Fame
    Even though I’ll walk in the church
    And burst in a ball of flames
    Only Hall of Fame I’ll be inducted in
    Is the alcohol of fame
    On the wall of shame
    You fags think it’s all a game
    ‘Til I walk a flock of flames
    Off a plank and, tell me what in the fuck are you thinkin’?
    Little gay-lookin’ boy
    So gay I can barely say it with a straight face
    Lookin’ boy (Ha-ha!)
    You’re witnessin’ a massacre
    Like you’re watching a church gathering take place, lookin’ boy
    “Oy vey, that boy’s gay!”—that’s all they say, lookin’ boy
    You get a thumbs up, pat on the back
    And a “way to go” from your label every day, lookin’ boy
    Hey, lookin’ boy! What you say, lookin’ boy?
    I get a “hell yeah” from Dre, lookin’ boy
    I’ma work for everything I have
    Never asked nobody for shit
    Get outta my face, lookin’ boy!
    Basically, boy, you’re never gonna be capable
    Of keepin’ up with the same pace, lookin’ boy, ’cause—
    I’m beginnin’ to feel like a Rap God, Rap God
    All my people from the front to the back nod, back nod
    The way I’m racin’ around the track
    Call me NASCAR, NASCAR
    Dale Earnhardt of the trailer park, the White Trash God
    Kneel before General Zod
    This planet’s Krypton—no, Asgard, Asgard
    So you’ll be Thor, I’ll be Odin
    You rodent, I’m omnipotent
    Let off, then I’m reloadin’
    Immediately with these bombs, I’m totin’
    And I should not be woken
    I’m the walkin’ dead, but I’m just a talkin’ head
    A zombie floatin’
    But I got your mom deep-throatin’
    I’m out my Ramen Noodle
    We have nothin’ in common, poodle
    I’m a Doberman, pinch yourself in the arm
    And pay homage, pupil
    It’s me, my honesty’s brutal
    But it’s honestly futile if I don’t
    Utilize what I do though
    For good at least once in a while
    So I wanna make sure somewhere in this
    Chicken scratch I scribble and doodle enough rhymes
    To maybe try to help get some people through tough times
    But I gotta keep a few punchlines
    Just in case, ’cause even you unsigned
    Rappers are hungry lookin’ at me like it’s lunchtime
    I know there was a time where once I
    Was king of the underground
    But I still rap like I’m on my Pharoah Monch grind
    So I crunch rhymes, but sometimes when you combine
    Appeal with the skin color of mine
    You get too big and here they come tryin’
    To censor you like that one line
    I said on “I’m Back” from The Mathers LP 1 when I
    Tried to say I’ll take seven kids from Columbine
    Put ’em all in a line, add an AK-47, a revolver and a 9
    See if I get away with it now
    That I ain’t as big as I was, but I’m
    Morphin’ into an immortal, comin’ through the portal
    You’re stuck in a time warp from 2004 though
    And I don’t know what the fuck that you rhyme for
    You’re pointless as Rapunzel with fuckin’ cornrows
    You write normal? Fuck being normal!
    And I just bought a new raygun from the future
    Just to come and shoot ya, like when Fabolous made Ray J mad
    ‘Cause Fab said he looked like a fag at Mayweather’s pad
    Singin’ to a man while he played piano
    Man, oh man, that was a 24-7 special on the cable channel
    So Ray J went straight to the radio station
    The very next day, “Hey Fab, I’ma kill you!”
    Lyrics comin’ at you at supersonic speed (J.J. Fad)
    Uh, summa-lumma, dooma-lumma, you assumin’ I’m a human
    What I gotta do to get it through to you I’m superhuman?
    Innovative and I’m made of rubber
    So that anything you say is ricochetin’ off of me
    And it’ll glue to you and
    I’m devastating, more than ever demonstrating
    How to give a motherfuckin’ audience
    A feeling like it’s levitating
    Never fading, and I know the haters are forever waiting
    For the day that they can say I fell off, they’ll be celebrating
    ‘Cause I know the way to get ’em motivated
    I make elevating music, you make elevator music
    “Oh, he’s too mainstream.”
    Well, that’s what they do when they get jealous
    They confuse it
    “It’s not hip-hop, it’s pop, “—’cause I found a hella way to fuse it
    With rock, shock rap with Doc
    Throw on “Lose Yourself” and make ’em lose it
    “I don’t know how to make songs like that
    I don’t know what words to use.”
    Let me know when it occurs to you
    While I’m rippin’ any one of these
    S that versus you
    It’s curtains, I’m inadvertently hurtin’ you
    How many verses I gotta murder to
    Prove that if you were half as nice
    Your songs you could sacrifice virgins too?
    Ugh, school flunky, pill junkie
    But look at the accolades these skills brung me
    Full of myself, but still hungry
    I bully myself ’cause I make me do
    What I put my mind to
    And I’m a million leagues above you
    Ill when I speak in tongues
    But it’s still tongue-in-cheek fuck you
    I’m drunk, so, Satan, take the fucking wheel
    I’ma sleep in the front seat
    Bumpin’ Heavy D and the Boyz
    Still “Chunky but Funky”
    But in my head there’s something
    I can feel tugging and struggling
    Angels fight with devils
    And here’s what they want from me
    They’re askin’ me to eliminate some of the women hate
    But if you take into consideration the bitter hatred
    I have, then you may be a little patient
    And more sympathetic to the situation
    And understand the discrimination
    But fuck it, life’s handin’ you lemons?
    Make lemonade then!
    But if I can’t batter the women
    How the fuck am I supposed to bake them a cake then?
    Don’t mistake him for Satan; it’s a fatal mistake
    If you think I need to be overseas and take a vacation
    To trip a broad, and make her fall on her face and
    Don’t be a retard — Be a king? Think not
    Why be a king when you can be a God?

LEAVE A REPLY

Please enter your comment!
Please enter your name here

seven + twelve =

Most Popular