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

The images on the carousel fail to load unless I adjust the window size

After investing countless hours into finding a solution, I am still unable to resolve this issue. The problem lies within my use of a Carousel and setting the images through a javascript file. Strangely enough, upon loading the page, only the first image ...

Animating elements within Firefox can sometimes cause adjacent elements to shift positions

Currently, I am working on a single-page website that utilizes keyboard-controlled scrolling. To achieve the desired scroll effect, I have developed a JavaScript function that animates divs. Here is the JavaScript code: var current_page = "#first"; func ...

Is there a CSS3-compatible CSS parser available in C/C++?

Are there any C/C++ CSS parsers that currently support CSS3? I have come across a few, but none of them seem to offer full CSS3 compatibility. ...

Allowing breaks with the :nth-child() selector

There must be a straightforward explanation for this perplexing issue. However, in my view, it ought to function as intended. We are currently utilizing the Bootstrap 3 CSS framework. The following code is present on a specific page: <div class="promo ...

What could be causing my function to output unicode replacement characters instead?

As I work on enhancing password security by implementing encryption, my goal is to store the hashes and perform encryption/decryption during signup/login processes. The encryption process works smoothly, converting from utf8 to hex without any issues. Howe ...

Encountering this error message while attempting to synchronize an Ionic Angular project in Xcode using npx cap sync

Every time I try to run npx cap sync on my Ionic Angular project in Xcode, I encounter the following error. [!] The plist file at path `/Users/user/Documents/GitHub/project-name/ios/App/App.xcodeproj/project.pbxproj` doesn't exist. I face the ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Is It Possible to Extract a Hidden Document Value from a Web Browser Using IWebBrowser2 in LabVIEW?

After hours of combing through the internet, I've come up empty-handed in my quest to find information related to my current project. I've created an HTML document that gathers user data and stores it in a JavaScript array. This array is then com ...

The integration between React.js, Node.js, and Express.js is facing issues with the socket.io functionality

I am currently working on integrating socket.io with React.js, running the socket.io on a backend server using Express.js. One issue I am facing is that when an order is placed on the homepage, it should be displayed in real-time on the Orders page in Rea ...

problem with selection of date and month in dropdown list with jquery

Recently, I've been dabbling in jQuery and decided to create two list boxes using it. One box contains dates while the other contains months. It's quite handy since I need them in different sections of my HTML page. However, when attempting to en ...

Is there a way to eliminate the blue formatting on my phone?

I've encountered a styling issue on my website when viewing it on mobile, specifically with links on iPhone. I've already attempted the solutions mentioned in this discussion: How do I remove the blue styling of telephone numbers on iPhone/iOS? ...

Does Firebase only send a single input value instead of a Span?

I am currently facing an issue with pushing data into my firebase database. I have successfully incorporated one user input field into the process. However, now I am attempting to include a span value in my database, which changes based on a slider that co ...

Looking to validate each input field individually using jQuery?

I am in need of validating all form inputs in the keyup function without having to write validation for each individual input. Is there a way to achieve this using methods like each();? Apologies for what may seem like a silly question. ' ...

Having difficulty sending a jQuery ajax() request to a PHP file

I am facing an issue with using the ajax() function. I have an HTML file containing a form and some JavaScript code: <script> $(document).ready(function(){ $("form").submit(function(){ var url = "xxx.php/"; ...

Excessive Blank Space Issue on Mobile Devices with MDBootstrap

I have been working on creating a replica of Watch2Gether, and it looks great on medium and large screens. However, when viewed on a phone, everything seems perfect until you scroll to the left and notice a large white space on the right side. I've ex ...

Passing data through events from a parent component to a child component in Vue.js using the $emit method

Having trouble making this work! I have included the $emit code in my click event to trigger a custom event. <h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="$emit('addBusinessHours', null)"> ...

Display a loading screen while retrieving information in React Redux

I have two sections on the page - a collection of IDs on the left side and data display on the right. When the page loads for the first time, all data related to every ID is shown. However, users can only select one ID at a time to view its specific data. ...

What is the best way to display an SVG file in a React application?

I am trying to figure out how to upload an SVG file and display a preview in a React component. I attempted to convert the SVG file into a React component by using the DOMParser to parse the SVG-XML string into a Document Object, but it is not functionin ...

Error encountered while using Jquery's .each() method on a DOM element and attempting to

Trying to utilize the each() function on my DOM to dynamically retrieve a field, I encountered an issue with the following code: var new_entry = new Object(); $('div[name="declaration-line-entry"]').each(function () { new_entry.name = $(this ...

When resizing the window, divs shift positions and prevent the use of the horizontal scrollbar

I'm encountering an issue with my website layout. Specifically, I have a full-width navbar with some divs nested within it. However, when the page is resized, the position of these divs in the navbar shifts and a scrollbar appears at the bottom of the ...