How to create a custom tabs without jQuery & Bootstrap
Here’s an example code snippet that creates hover tabs using HTML, CSS, and JavaScript:
01. Step
<div class="tab"> <button class="tablinks" onclick="openTab(event, 'Tab1')">Tab 1</button> <button class="tablinks" onclick="openTab(event, 'Tab2')">Tab 2</button> <button class="tablinks" onclick="openTab(event, 'Tab3')">Tab 3</button> </div> <div id="Tab1" class="tabcontent"> <h3>Tab 1 content</h3> <p>Some text goes here.</p> </div> <div id="Tab2" class="tabcontent"> <h3>Tab 2 content</h3> <p>Some more text goes here.</p> </div> <div id="Tab3" class="tabcontent"> <h3>Tab 3 content</h3> <p>Even more text goes here.</p> </div>
02. Step
function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " active"; }
03. Step
.tab { overflow: hidden; border: 1px solid #ccc; background-color: #f1f1f1; } .tab button { background-color: inherit; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; transition: 0.3s; } .tab button:hover { background-color: #ddd; } .tab button.active { background-color: #ccc; } .tabcontent { display: none; padding: 6px 12px; border: 1px solid #ccc; border-top: none; }
In this code, we have a div element with class tab that contains three button elements with class tablinks. Each button has an onclick event that calls the openTab() function and passes the event object and the corresponding tab name as arguments.
We also have three div elements with class tabcontent that contain the content for each tab. These div elements are hidden by default using the display: none; CSS property.
The openTab() function takes the tab name as input and sets the display style of all tabcontent elements to none, removes the active class from all tablinks elements, sets the display style of the corresponding tabcontent element to block, and adds the active class to the corresponding tablinks element.
Finally, we have some CSS styling that sets the appearance of the tabs and the content. The hover and active states of the tablinks are defined using CSS :hover and :active pseudo-classes, respectively.