Change Content Nav on Click Using CSS

Change Content Nav on Click Using CSS

Navigating through a website should be a smooth and engaging experience. One way to enhance user interaction is by changing the content displayed when a navigation item is clicked. This can be achieved using CSS and a bit of JavaScript and also can be achieved just using CSS. In this article, we’ll explore how to create a dynamic navigation system that changes content on click. There are 2 examples, in the first example we will explore “change content nav on click using CSS and JavaScript” and the Second example will just use CSS.

Understanding the Basics

Before diving into the code, let’s understand what we aim to achieve. Imagine a website with a navigation menu. The content area updates to show relevant information without reloading the page when you click on a menu item. This technique is commonly used in single-page applications (SPAs) to provide a seamless user experience.

i. Example of Change Content Nav on Click Using CSS & JavaScript

In this example, we use CSS and JavaScript.

Change Content Nav on Click Using CSS
Change Content Nav on Click Using CSS

1. Setting Up the HTML Structure

First, we need a simple HTML structure. We’ll create a navigation menu and a content area where the content will change based on the clicked navigation item.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Navigation</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <nav>
        <ul>
            <li><a href="#" data-content="home">Home</a></li>
            <li><a href="#" data-content="about">About</a></li>
            <li><a href="#" data-content="services">Services</a></li>
            <li><a href="#" data-content="contact">Contact</a></li>
        </ul>
    </nav>
    <div id="content">
        <p>Welcome to our website! Click on the navigation items to see more content.</p>
    </div>
    <script src="script.js"></script>
</body>
</html>

2. Styling with CSS

Next, we’ll add some basic CSS to style our navigation menu and content area. This will make our page look neat and visually appealing.

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

nav {
    background-color: #333;
    color: #fff;
    padding: 10px 0;
}

nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    justify-content: center;
}

nav ul li {
    margin: 0 15px;
}

nav ul li a {
    color: #fff;
    text-decoration: none;
    padding: 10px 20px;
    display: block;
}

nav ul li a:hover {
    background-color: #575757;
}

#content {
    padding: 20px;
    text-align: center;
}

3. Adding Interactivity with JavaScript

We will use JavaScript to make the content change dynamically. We’ll add an event listener to each navigation item that updates the content area when clicked.

document.addEventListener('DOMContentLoaded', function() {
    const navLinks = document.querySelectorAll('nav ul li a');
    const contentDiv = document.getElementById('content');

    navLinks.forEach(link => {
        link.addEventListener('click', function(event) {
            event.preventDefault();
            const content = this.getAttribute('data-content');
            updateContent(content);
        });
    });

    function updateContent(content) {
        let htmlContent = '';

        switch(content) {
            case 'home':
                htmlContent = '<p>Welcome to the Home page!</p>';
                break;
            case 'about':
                htmlContent = '<p>Learn more About us on this page.</p>';
                break;
            case 'services':
                htmlContent = '<p>Discover our Services here.</p>';
                break;
            case 'contact':
                htmlContent = '<p>Get in touch with us on the Contact page.</p>';
                break;
            default:
                htmlContent = '<p>Welcome to our website! Click on the navigation items to see more content.</p>';
        }

        contentDiv.innerHTML = htmlContent;
    }
});

How It Works

1. HTML Structure:

  • We start with a basic HTML structure that includes a navigation menu and a content area.
  • The navigation menu consists of an unordered list (<ul>) with list items (<li>), each containing an anchor tag (<a>).
  • Each anchor tag has a data-content attribute. This attribute holds the identifier for the content that should be displayed when the link is clicked. For example, <a href="#" data-content="home">Home</a>.

2. CSS Styling:

  • The CSS is used to style the navigation menu and the content area to make them visually appealing.
  • The body tag is styled to set the font family, margin, padding, and background color.
  • The nav element is styled to have a background color, text color, and padding.
  • The ul inside the nav is styled to remove default list styles and to display the list items horizontally using display: flex and justify-content: center.
  • Each li and a tag is styled to ensure proper spacing, color, and hover effects. The hover effect changes the background color of the links when the mouse is over them.
  • The #content div is styled to add padding and center-align the text.

3. JavaScript Interactivity:

  • JavaScript is used to add interactivity to the navigation links.
  • We use document.addEventListener('DOMContentLoaded', function() {...}) to ensure the script runs after the DOM is fully loaded.
  • We select all navigation links using document.querySelectorAll('nav ul li a') and store them in the navLinks variable.
  • We select the content div using document.getElementById('content') and store it in the contentDiv variable.
  • We loop through each link in navLinks and add an event listener for the click event.
  • When a link is clicked, the default action (which would normally reload the page) is prevented from using event.preventDefault().
  • The data-content an attribute of the clicked link is retrieved using this.getAttribute('data-content').
  • The updateContent a function is called with the retrieved content identifier.
  • Inside the updateContent function, a switch statement is used to determine which content to display based on the content identifier.
  • The innerHTML of the contentDiv is updated with the corresponding HTML content.

By following these steps, we create a dynamic navigation system that updates the content area based on the clicked navigation item, providing a seamless and engaging user experience.

ii. Example of Change Content Nav on Click Using CSS

In this example we just use HTML and CSS it is possible to change content navigation on click using only CSS:-

1. HTML Structure

First, let’s set up the HTML structure. We’ll use anchor links to navigate between different sections of content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Navigation with CSS</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <nav>
        <ul>
            <li><a href="#home">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#services">Services</a></li>
            <li><a href="#contact">Contact</a></li>
        </ul>
    </nav>
    <div id="content">
        <section id="home">
            <p>Welcome to the Home page!</p>
        </section>
        <section id="about">
            <p>Learn more About us on this page.</p>
        </section>
        <section id="services">
            <p>Discover our Services here.</p>
        </section>
        <section id="contact">
            <p>Get in touch with us on the Contact page.</p>
        </section>
    </div>
</body>
</html>

2. CSS Styling

Next, we’ll add CSS to style the navigation and content sections. We’ll use the :target pseudo-class to display the content based on the clicked link.

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

nav {
    background-color: #333;
    color: #fff;
    padding: 10px 0;
}

nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    justify-content: center;
}

nav ul li {
    margin: 0 15px;
}

nav ul li a {
    color: #fff;
    text-decoration: none;
    padding: 10px 20px;
    display: block;
}

nav ul li a:hover {
    background-color: #575757;
}

#content section {
    display: none;
    padding: 20px;
    text-align: center;
}

#content section:target {
    display: block;
}

How It Works

1. HTML Structure:

  • We have a navigation menu with links. Each link points to a different section using an anchor (href="#section-id").
  • The content is divided into sections, each with a unique id that matches the anchor links.

2. CSS Styling:

  • The body and nav elements are styled to set the font, background color, and layout.
  • The nav ul is styled to display the list of items horizontally.
  • Each li and a tag is styled for proper spacing, color, and hover effects.
  • The #content section elements are initially hidden using display: none.
  • The :target pseudo-class is used to display the section that matches the clicked link. When a link is clicked, the corresponding section becomes visible (display: block).

By using the :target pseudo-class, we can create a dynamic navigation system that changes the displayed content based on the clicked link, all without using JavaScript. This method leverages CSS to provide a smooth and engaging user experience.

Benefits of Dynamic Navigation

  • Improved User Experience: Users can navigate through the content without page reloads, making the experience smoother and faster.
  • SEO Friendly: Since the content is loaded dynamically, search engines can still index the main page and its content.
  • Easy to Maintain: Updating the content or adding new sections is straightforward, as you only need to modify the HTML and JavaScript.

Conclusion

Changing content navigation on click using CSS and JavaScript is a powerful technique to enhance user interaction on your website. By following the steps outlined in this article, you can create a dynamic and engaging navigation system that improves the overall user experience. Whether you’re building a personal blog, a business website, or a portfolio, this approach can make your site more interactive and user-friendly.

Author: Jahid Shah

An Expert WordPress Developer and Security Specialist with over 5 years of experience in theme installation, customization, frontend design, Malware Remove and Bug Fixing. I...

View all posts by Author

Follow Author: