How to Change Tabs on Hover with CSS and JavaScript

In web design, having the ability to create interactive and engaging navigation is crucial for the user experience.

Tabs are a popular form of navigation that allows users to access different sections of a webpage with ease.

In this tutorial, we will explore how to change tabs on hover using CSS and JavaScript.


CSS for Tab Navigation

To create a basic tab navigation in HTML, we will start with an unordered list with list items as the tab buttons.

We will use CSS to style these list items as tabs and also add hover effects. Here is the code for our tab navigation:

<ul class="tab-nav">
  <li class="tab">Tab 1</li>
  <li class="tab">Tab 2</li>
  <li class="tab">Tab 3</li>
</ul>

.tab-nav {
  list-style: none;
  display: flex;
  justify-content: space-between;
  padding: 0;
}

.tab {
  background-color: #ddd;
  padding: 10px 20px;
  text-align: center;
  cursor: pointer;
}

.tab:hover {
  background-color: #ccc;
}

JavaScript for Tab Content

Now that we have our tab navigation styled, we will add JavaScript to display the content for each tab.

We will use JavaScript to hide all the tab content and only display the content for the selected tab.

Here is the code for our tab content:

<div class="tab-content">
  <div class="content">
    Content for Tab 1
  </div>
  <div class="content">
    Content for Tab 2
  </div>
  <div class="content">
    Content for Tab 3
  </div>
</div>

.content {
  display: none;
}

const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.content');

tabs.forEach((tab, index) => {
  tab.addEventListener('mouseenter', () => {
    tabContents.forEach(content => {
      content.style.display = 'none';
    });
    tabContents[index].style.display = 'block';
  });
});

Conclusion

In this tutorial, we have explored how to change tabs on hover using CSS and JavaScript.

By combining HTML, CSS, and JavaScript, we were able to create a basic tab navigation with hover effects and dynamic content display.

With a few modifications, this tab navigation can be adapted to fit the needs of your website.

Try experimenting with different hover effects and styles to make your tab navigation unique and engaging for your users.