Display the selected tab or menu option as the highlighted element using JavaScript

This is not a jQuery inquiry. I am utilizing neither an <anchor> nor a list for my menu structure. My goal is to have the tab item in the menu appear in a different color when it is active. CSS pseudo-classes such as :active and :selection did not yield the desired outcome. The layout of my menu involves using a <label> within a <p> tag:

<div id="MainMenu">
   <p class="floatLeftP" id="SiteName">Site Name Here</p>
   <p class="floatLeftP"><label id="ViewLink1" onclick="mainMenuChg('Home')">HOME</label></p>
   <p class="floatLeftP"><label id="ViewLink2" onclick="mainMenuChg('Offered')">OFFERED</label></p>
   <p class="floatLeftP"><label id="ViewLink3" onclick="mainMenuChg('Input')">INPUT</label></p>
   <p class="floatLeftP"><label id="ViewLink4" onclick="mainMenuChg('Wanted')">WANTED</label></p>
   <p class="floatLeftP"><label id="ViewLink5" onclick="mainMenuChg('MyAccount')">My Account</label></p>
   <p class="floatLeftP"><label id="ViewLink6" onclick="openHTTPS()">Sign Up!</label></p>
   <p class="floatRightP"><label id="ViewLink7" onclick="openHTTPS()">Sign In</label></p>    
</div>

The usage of CSS :active typically applies to links, which are not being utilized in my setup.

Upon clicking most of the menu items, a function named mainMenuChg('argHere') is executed.

function mainMenuChg(argPage) {
    window.location.href = "#" + argPage;
};

This adjustment in the URL triggers an AngularJS router, however, I prefer employing only JavaScript without involving AngularJS. By using the code below, I can alter the color of a menu item:

document.getElementById(theID).style.color = "yellow";

However, the color remains unchanged once set. Clicking on another menu item results in multiple yellow-colored items. The desired functionality is to change the color of the current <label> while returning the previous one to its original color. Since each menu item has a distinct color, resetting to the default hue is indispensable.

I am seeking a method to retain the value of the old id without losing it by storing it in a variable. Defining the variable within the function appears to result in loss of its value.

While there are some jQuery solutions available, I specifically require a JavaScript-based approach.

Answer №1

Begin by assigning a class to all the labels.

For instance, use class="tab-label".

You can then make some modifications to the function and include an extra parameter.

function changeTab(pageName,labelId)
.

Update the labels to include...

onclick="changeTab('Homepage',this.id)">

Now let's dive into the function itself...

function changeTab(pageName,labelId) {
    //Remove existing color from all tabs
    var labels = document.getElementsByClassName("tab-label");
    //Loop through each label
    for(var i=0; i< labels.length; i++)
    {
         labels[i].style.color = "grey";
    }
    //Apply specific color to the clicked tab
    document.getElementById(labelId).style.color = "green";
    window.location.href = "#" + pageName;
};

Answer №2

You can try out the code snippet below to see if it solves your issue:

let prevElement; // global variable.

if(prevElement !== undefined) {
  prevElement.style.color = original_color;
}
this.style.color = "yellow";
prevElement = this;

Answer №3

With the generous contributions of everyone here, I have successfully devised a functional solution. You can find a complete working version on jsFiddle by following the link provided below. Take a look at the HTML snippet:

<div id="menu">
    <ul>
        <li><a class="myMenu" id="xyz1" href="#" title="Update"><span>Home</span></a>

        </li>
        <li><a class="myMenu" id="abc2" href="#" title="Save"><span>Save</span></a>

        </li>
        <li><a class="myMenu" id="hij9" href="#" title="User"><span>User</span></a>

        </li>
    </ul>
</div>

Here is the code implementation:

var menuHome = document.getElementById('xyz1');
var menuSave = document.getElementById('abc2');
var menuUser = document.getElementById('hij9');

menuHome.addEventListener('mouseup', clickedHome, false);
menuSave.addEventListener('mouseup', clickedSave, false);
menuUser.addEventListener('mouseup', clickedUser, false);

var currentMenuItem = '';

function clickedHome() {
    if (menuHome === currentMenuItem) {
        return;
    };
    //alert("home menu clicked: ");
    menuHome.style.background = 'blue';
    //alert('currentMenuItem: ' + currentMenuItem);
    if (currentMenuItem !== undefined && currentMenuItem !== "") {
        //alert("it ran: ");
        currentMenuItem.style.background = '';
    }
    setCurrent(menuHome);
}

function clickedSave() {
    if (menuSave === currentMenuItem) {
        return;
    };
    //alert("home menu clicked: ");
    menuSave.style.background = 'cyan';
    if (currentMenuItem !== undefined && currentMenuItem !== "") {
        //alert("it ran: ");
        currentMenuItem.style.background = '';
    }
    setCurrent(menuSave);
}

function clickedUser() {
    //alert("home menu clicked: ");
    if (menuUser === currentMenuItem) {
        return;
    };
    menuUser.style.background = 'blue';
    if (currentMenuItem !== undefined && currentMenuItem !== "") {
        //alert("it ran: ");
        currentMenuItem.style.background = '';
    }
    setCurrent(menuUser);
}

function setCurrent(argMenu) {
    //alert("set current ran: ");
    currentMenuItem = argMenu;
    //alert('currentMenuItem: ' + currentMenuItem);
};

Experience this in action yourself by visiting the provided jsFiddle link.

Highlight Active Menu Item on Menu Bar

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

File Uploading with JavaScript

Imagine you have an element on your webpage like this: <input id="image-file" type="file" /> With this element, users can click a button to select a file through their browser's "File open..." dialog. If a user selects a file and clicks "Ok" ...

Unable to use the .focus() method on a Link component by utilizing references in React Router 4

I am currently working with the Link component in react-router (v4). I have successfully attached a ref to this component and can log the reference. However, when I try to use linkRef.current.focus(), I encounter the following error: linkRef.current.focu ...

Changing data in Chart.js, strategies for modifying data after chart creation!

Apologies if this question seems basic. The challenge I am facing is that I need to utilize the same data for multiple charts, but with slight variations in options for each chart. The data is as follows: var data = { labels: freq, datase ...

The content div sits atop the full-width image instead of being displaced downwards

Featuring a stunning full-width image: .image { background-image: url(http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2014/06/wallpaper_51.jpg); background-position: center center; background-repeat: !important; position: absolute; ...

Ensuring IconButton is perfectly aligned with Text in one straight line

I want to display IconButtons alongside plain text in a single block of text, but the result didn't turn out as I had hoped. Here is what I attempted: JS(ReactJS): <div> <span> <h3>Title</h3> <IconButton className ...

Changing the arrow in jQuery's slideToggle for different div elements is a breeze

Good day, I'm struggling with getting the arrow switch to work correctly for slideToggle. Even though I have three of them, the arrow changes only for the first one - no matter which div I click on. Any suggestions on what I might be missing? Thank yo ...

I am currently working on creating a basic task tracker using Express, however, I am encountering difficulties in getting the 'delete' button to function properly

Struggling to implement a simple to do list with a "delete" button that doesn't seem to be working? No errors are popping up, but the button remains unresponsive. Various attempts have been made to fix this issue without success. Uncertain whether the ...

Using Jquery and AJAX to dynamically fill out an HTML form based on dropdown selection

My goal is to populate a form on my webpage with information pulled from a MySQL database using the ID of the drop-down option as the criteria in the SQL statement. The approach I have considered involves storing this information in $_SESSION['formBoo ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

What steps can I take to create a responsive jQuery UI buttonset?

I am currently facing a challenge with my web app (http://www.tntech.edu/cafe-menu.php) which is being iframed into a mobile application developed by ATT. The button sizes vary on different phone models, and I am seeking a solution to make them responsiv ...

By simply clicking the link, the content comes to life with animation

Is there a way to replicate the scrolling effect seen on this website ? The content shifts to the left and reveals new site content. Please excuse my English. ...

What is the best way to create a cube in Three.js with the 4 corner points of the base and a specified height?

Given a JSON with base coordinates, I am looking to generate a cube in Three.js. The height of the cube will be a constant value, such as 1. { "points": [ { "x": 0, ...

parallelLimit asynchronously executes in limited quantities once

Utilizing async.parallelLimit to update database records in batches of 10 that total 1000 each time is my current challenge. I am exploring how to implement this feature in my code but have run into some issues. Despite studying example interpretations, my ...

Is it possible for me to trigger a custom event using an eventBus listener?

In the Vue component, I have the following setup: data: function() { return { quotes: [] }; }, created() { eventBus.$on("quoteWasAdded", message => { this.quotes.push(message); this.$emit("quotesWereUpdated", this.quot ...

Setting the background color for a div in Vue.js when importing HTML

Check out this HTML code snippet <!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Getting Started: Serving Web Content< ...

Why is this regular expression failing to match German words?

I am attempting to separate the words in the following sentence and enclose them in individual span elements. <p class="german_p big">Das ist ein schönes Armband</p> I came across this: How to get a word under cursor using JavaScript? $(&ap ...

Guide on creating a toggle effect for a div with querySelector and addEventListener

I utilized the email and password divs provided by Bootstrap. The CSS for the id dropdownlogin includes display: none; in this post, I hope that I have shared adequate information. <script> document.addEventListener('DOMContentLoaded', ...

Is it possible to utilize Javascript instead of PHP Curl to present JSON API data?

After successfully displaying JSON API data from openweathermap.org on my HTML webpage using PHP Curl, I am now seeking help to achieve the same output using Javascript. My PHP script retrieves JSON data from the source, and here is a snippet of that PHP c ...

Updating a URL for all users using React/Next.js and Firebase: a guide to refreshing the page

I am currently developing a Next.js application with a Firebase backend and have encountered an issue. In my setup, users can create sessions that others can join, but only the creator of the session can "start" it, triggering a state change. I need all us ...