How to Implement Tabs jQuery From Scratch

In this tutorial we will implement tabs in jquery from scratch without any plugin. This is a very basic task because in a few lines of code we will be able to implement this functionality. Before proceed with the implementation please make sure you already have jquery added to your website, if not go on google and get the cdn for lateste version of jquery.

Implement Tabs jQuery From Scratch

First step is to create the buttons which will trigger the content section. The HTML structure should look like the following structure:

<ul class="trigger_buttons">
  <li><a href="#content1">Button 1</a></li>
  <li><a href="#content2">Button 2</a></li>
  <li><a href="#content3">Button 3</a></li>
  <li><a href="#content4">Button 4</a></li>
  <li><a href="#content5">Button 5</a></li>
</ul>

Now, let's create few lines of css to style the buttons a little.

.trigger_buttons{
  text-align:center;
        margin-bottom:20px;
}
.trigger_buttons li{
  display:inline-block;
  padding:0 15px;
}
.trigger_buttons li a{
  font-size:14px;
  color:#fff;
  display:block;
  padding:15px 25px;
  border-radius:5px;
  background:black;
}
.content_tabs .content{
  display:none;
}
.content_tabs .content:first-child{
  display:block;
}

We have the buttons, but we still need the content structure. When we will click on the button we will get the href attribute and then we will find the div content with the same id and show it.

The content structure part:

<div class="content_tabs">
  <div id="content1" class="content">
    <p>My content structure</p>
  </div>
  <div id="content2" class="content">
    <p>My content structure</p>
  </div>
  <div id="content3" class="content">
    <p>My content structure</p>
  </div>
  <div id="content4" class="content">
    <p>My content structure</p>
  </div>
  <div id="content5" class="content">
    <p>My content structure</p>
  </div>
</div>

 

We are almost ready with the implementation, the last thing we need to add is our jquery code. In order to make this functionality works add the following code to your site:

jQuery('.trigger_buttons a').on('click', function(e){
  e.preventDefault();
  var get_id = jQuery(this).attr('href');
  jQuery('.content_tabs .content').hide();
  jQuery('.content_tabs '+get_id).fadeIn();
});

As you can see in the above function, when you click on the button we get its value from href attribute. Then we will use the id to target the right content div and show it. Let me know if you have any questions.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x