JavaScript multi-click navigation menu

I'm relatively new to JavaScript and I've been struggling with using multiple onClick attributes. While I have some code that works, I feel like there might be a simpler and cleaner solution to my problem.

What I'm trying to achieve is a navigation menu where clicking on a hyperlink changes its background color and updates the content of a blog div. Additionally, when clicking on another hyperlink, it should change the background color and reset the previous one to its original state.

Here's what I have so far. It seems to work, but I'm not sure if this is the most efficient approach:

-- HTML

<div id="container">
    <div id="navigation_bar">
        <nav>
            <ul>
                <li class="red" id="1"><a href="#" onclick="showDiv1(this)">NavMenu1</a></li>
                <li class="red" id="2"><a href="#" onclick="showDiv2(this)">NavMenu2</a></li>
                <li class="red" id="3"><a href="#" onclick="showDiv3(this)">NavMenu3</a></li>
                <li class="red" id="4"><a href="#" onclick="showDiv4(this)">NavMenu4</a></li>
            </ul>
        </nav>
    </div>
    <div id="blog">
        <div id="category_1" style="display: none">
            <img src="#" alt="xx" />
            <article>
                <p>Content of first navigation bar</p>
            </article>
        </div>
        <div id="category_2" style="display: none;">
            <article>
                <p>Content of second navigation button</p>
            </article>
        </div>
    </div>
</div>

JavaScript

function showDiv1(obj) {
    var elchosen = document.getElementById('category_1');
    elchosen.setAttribute('style', 'display:block;');

    var spanID = obj.parentNode.id;
    var newNode = document.getElementById(spanID);

    var menus = document.getElementsByClassName("rood");
    for (var i = menus.length - 1; i >= 0; i--) {
        var elem = document.getElementById(menus[i].id);
        elem.style.backgroundColor = "transparent";

    }

    newNode.style.backgroundColor = "red";
}

function showDiv2(obj) {

    var elchosen = document.getElementById('category_1');
    elchosen.setAttribute('style', 'display:none;');

    var elchosen = document.getElementById('category_2');
    elchosen.setAttribute('style', 'display:block;');

    var spanID = obj.parentNode.id;
    var newNode = document.getElementById(spanID);

    var menus = document.getElementsByClassName("red");
    for (var i = menus.length - 1; i >= 0; i--) {
        var elem = document.getElementById(menus[i].id);
        elem.style.backgroundColor = "transparent";

    }

    newNode.style.backgroundColor = "red";
}

It would be great if there's a more concise way to achieve this, perhaps using categories and functions like showDiv(n), to avoid repeating similar code for different operations as shown above.

Any advice or tips would be greatly appreciated, as I'm still learning and exploring JavaScript. Thank you!

Answer №1

If the question pertains to jQuery, I will provide a solution using that framework. You can update your JavaScript code with the following:

// Utilize event delegation by setting up a click event for all "a" elements within the #navigation_bar
$('#navigation_bar').on('click', 'a', function(){
   // Retrieve the closest <li> element containing the clicked link
   var li = $(this).closest('li');

   // Conceal all blog sections. It's recommended to categorize them within <div> tags like $('.category', '#blog');
   $('#blog > div').hide();
   
   // Display the desired section based on the id of the clicked <li>
   $('#category_' + li.attr('id')).show();

   // Instead of specifying colors directly, toggle classes. Remove the red class from all menu items
   $('li', '#navigation_bar').removeClass('red');
   
   // Add the red class to the activated menu item
   li.addClass('red');
});

Answer №2

A simple solution to the issue can be achieved by utilizing anchors and CSS with :target selector. By modifying your HTML code like this:

<li class="blue" id="5"><a href="#section_1">Menu1</a></li>
<li class="blue" id="6"><a href="#section_2">Menu2</a></li>
<li class="blue" id="7"><a href="#section_3">Menu3</a></li>
<li class="blue" id="8"><a href="#section_4">Menu4</a></li>

and then applying the following CSS rules:

#content>section {
 display:none;
}

#content>section:target {
 display:block;
}

This method will effectively show and hide the content sections without the need for Javascript, except for managing the menu items. You can implement a basic jQuery function to change the navigation colors as shown below:

$('nav ul li a').click(function(){
   $('nav ul li').removeClass('blue');
   $(this).parent().addClass('blue');

   //Add this line if you want to scroll to the top of the page instead of the section
   window.setTimeout(function(){ window.scrollTo(0,0); }, 0);
});

Answer №3

/*save this file as script.js*/


function ChangePagetoHome()
{

    $("#A").show();
    $("#B").hide();
    $("#C").hide();

}


function ChangePagetoContact()
{
    $("#A").hide();
    $("#B").show();
    $("#C").hide();

}


function ChangePagetoProfile()
{
    $("#A").hide();
    $("#B").hide();
    $("#C").show();

}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8>
    <title>Menu</title>
    <script src="script.js"></script>
    <script src="jquery-1.11.2.min.js"></script>

</head>
<body>

<div id="A">
    <nav>
        <ul>
            <li><a class="active" onclick="ChangePagetoHome();">Home</a></li>
            <li><a onclick="ChangePagetoContact();">Contact us</a></li>
            <li><a onclick="ChangePagetoProfile();">My profile</a></li>
        </ul>
    </nav>
    <p>Hi I Am Home</p>
</div>

<div id="B" style="display: none;">
    <nav>
        <ul>
            <li><a onclick="ChangePagetoHome();">Home</a></li>
            <li><a class="active" onclick="ChangePagetoContact();">Contact us</a></li>
            <li><a onclick="ChangePagetoProfile();">My profile</a></li>
        </ul>
    </nav>
    <p>Hi I Am Contact</p>
</div>

<div id="C" style="display: none;">
    <nav>
        <ul>
            <li><a  onclick="ChangePagetoHome();">Home</a></li>
            <li><a onclick="ChangePagetoContact();">Contact us</a></li>
            <li><a class="active" onclick="ChangePagetoProfile();">My profile</a></li>
        </ul>
    </nav>
    <p>Hi I Am Profile</p>
</div>


</body>
</html>

This is a basic JavaScript navigation menu example. Remember to include jQuery and avoid using href="#" in the code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

.class selector malfunctioning

I'm currently developing a card game system where players can select a card by clicking on it and then choose where to place it. However, I've encountered an issue where nothing happens when the player clicks on the target place. Here is the li ...

What could be the reason why the border of my table displays in Firefox and Chrome, but remains hidden in Internet Explorer

I am facing an issue with getting a border to display on a table in Internet Explorer versions IE6, IE7, and IE8. The border is showing up fine in Chrome and Firefox but not in the mentioned IE versions. Below is the CSS code that I have been using: #info ...

Using jQuery to update the CSS class for all li icons except for the one that is currently selected

Utilizing Font Awesome Icons within the li elements of a ul Challenge When a user clicks on the user icon, the color changes from black to yellow. If the user clicks on another icon, that one also turns yellow. Is there a way to remove the existing yell ...

Enhance your search experience with AJAX-powered search boxes

I need to implement multiple textboxes on my webpage, each with its own search query to retrieve data from the database. While I have successfully implemented this for one textbox, I am facing difficulties getting it to work for two or more textboxes. He ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

Utilizing Promises in the apply function

I am currently working on a project in Node.js that utilizes bluebird for promise handling, as well as ES6 native promises. In both projects, I have a chain where I make a database query structured like this: some_function(/*...*/) .then(function () ...

Error encountered during Heroku deployment: "sh: 1: tailwind: not found"

package.json: "devDependencies": { "tailwindcss": "^0.7.4" }, "scripts": { "tailwind:css": "tailwind build src/css/tailwind.src.css -c tailwind.js -o src/css/tailwind.css", "start": "npm run tailwind:css && react-scripts start", ...

The size of table cells automatically adjusts when zooming in the browser

While trying to display my table in Chrome, I noticed that the cell sizes of the table change when zooming in. Additionally, the table is rendered incorrectly in other browsers like IE and Firefox. I attempted adjusting the sizes to percentage values but i ...

Exploring techniques for creating realistic dimensions in CSS

My goal is to create a responsive website that accurately displays an object with specified dimensions, such as a width of 100mm, regardless of the user's screen resolution. However, I am facing challenges in achieving this consistency across all devi ...

Generate clickable links on a web page with PHP and a form

Every week I find myself tediously creating links by manually copying and pasting. It's starting to feel like a crazy process, and I'm sure there must be a faster way. A123456 B34567 d928333 s121233 I need these numbers to be transformed into h ...

Utilizing ReactJS and Gatsby Js: How to pass the value of a child component to the parent component to create a button

In my current project, I am facing an issue with a simple component that is supposed to pass back the link value from the child component to a function in the parent component. However, it seems to only call back the full function instead of its actual v ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...

What is the method to access and examine the attributes of a range in Office.js?

I am encountering an issue while attempting to retrieve the values from cell B2 and create a conditional statement based on those values. Despite my efforts, I continue to receive an error message without any clear understanding of its cause. Please refe ...

Unable to retrieve basic profile data from LinkedIn Members using their email ID unless they are signed in

I am struggling to retrieve the basic profile details of Linkedin Members using their email ID. Despite my efforts, I haven't been able to find relevant information in the documentation. My attempt involved creating an app, initializing the JavaScrip ...

Discover the power of the "Load More" feature with Ajax Button on

After browsing through the previous questions and experimenting with various techniques, I've come close to a solution but still can't get it to work. The closest example I found is on Stack Overflow: How to implement pagination on a custom WP_Qu ...

Validation is not being enforced for the input field labeled as 'name' in the form

Can anyone assist me with a form validation issue I'm encountering while working on my project? The validation is functioning correctly for email and institution fields, but it seems to be ignoring the name field. Any suggestions or help would be grea ...

How can I use AJAX to read a CSV file uploaded by a client in C#?

My current project involves the scenario where a user needs to choose a CSV file from their local system. It is then necessary for me to read the contents of this file and display them on a JQGrid. The catch? This all needs to work smoothly in Internet E ...

Tips for delaying the rendering of a directive in AngularJS until the data from a tsv file has been fully loaded

I am trying to integrate d3.js with angularjs to create a line graph using data loaded from a tsv file. However, I am facing an issue where the graph is being rendered before the data is fully loaded. I want the graph to be rendered only after the data has ...

Transitioning smoothly between different backgrounds will be like changing the cursor color

As I work on my website, I encounter the need for a cursor that smoothly changes its color. Specifically, I want the cursor to appear blue (#0059ff) when hovering over a white background and white when over a blue background, with a seamless transition lik ...