adjusting the font color based on the currently selected tab

After seeking help for my previous question on Unable to add a background colour to the button in navigation

I have successfully resolved that issue and continued working, but now I am facing a new challenge. I need to change the font color of the navigation bar elements based on which tab is currently active. The CSS appears correct as it styles the "currently active" tab correctly, so it seems like the JavaScript part is where the problem lies.

var header = document.getElementById("navbar");
var btns = header.getElementsByClassName("topnavbar");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
 .active {
    text-decoration: none;
    color: #4da6ff;
    outline: none;  
 }
<div id="navbar" >
   <ul>
       <li> <a class="topnavbar active" href="" id="home"title="Home">HOME </a> </li>
       <li> <a class="topnavbar"        href="" id="movies" title="Movies">MOVIES </a> </li>
       <li> <a class="topnavbar"        href="" id="theaters" title="Theaters">THEATERS </a></li>
       <li> <a class="topnavbar"        href="" id="buytickets" title="Buy Tickets Online">BUY TICKETS ONLINE </a> </li>
       <li style="float:right"><a class="btn btn-scope1 navbar-btn" id="btn1" href="">TEST YOUR KNOWLEDGE </a> </li>
    </ul>
</div>

What could be the mistake in my approach?

Answer №1

Have a look below, I have copied your code exactly as it is and it seems to be working perfectly fine. The only modification I made was adding "#" to your href so that the link stays on the same page.

var header = document.getElementById("navbar");
var btns = header.getElementsByClassName("topnavbar");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
 .active {
    text-decoration: none;
    color: #4da6ff;
    outline: none;
    background: #34495e;
 }
<div id="navbar" >
   <ul>
       <li> <a class="topnavbar active" href="#" id="home"title="Home">HOME </a> </li>
       <li> <a class="topnavbar"        href="#" id="movies" title="Movies">MOVIES </a> </li>
       <li> <a class="topnavbar"        href="#" id="theaters" title="Theaters">THEATERS </a></li>
       <li> <a class="topnavbar"        href="#" id="buytickets" title="Buy Tickets Online">BUY TICKETS ONLINE </a> </li>
       <li style="float:right"><a class="btn btn-scope1 navbar-btn" id="btn1" href="">TEST YOUR KNOWLEDGE </a> </li>
    </ul>
</div>

Answer №2

After following your advice, I was able to successfully resolve the issue with my script. Previously, I had placed the script tag where it seemed logical - inside the <head> tag. However, as suggested by all of you, moving it within the body tag proved to be the correct solution. Apologies for any inconvenience caused and appreciation to those who offered their assistance.

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

Working with HTTPS in Angular: A guide to using $http

Can anyone provide guidance on how to handle https + cross-domain URL using $http? I managed to solve my issue using $.ajax, but I prefer using $http because I have an $http interceptor set up to automate certain processes. I've checked out related ...

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...

Guide on keeping your MongoDB collection up-to-date with Mongoose

I'm currently facing an issue while working on a project. My goal is to build a MongoDB database where I can store dates and YouTube video links. I've chosen to use Mongoose as my ORM. The problem I'm encountering is that while I can create ...

Setting the initial date value for an Angular Material md-datepicker to a specific date

When using Angular Material md-datepicker, by default the system's current date is set as today's date and highlighted in the calendar. However, I am looking for a way to manually set any given date as today's date instead. Please see this i ...

The scrolling feature in the option list for Adobe Air Client and Javascript appears to be non-functional

I am currently utilizing Air Client in conjunction with HTML, CSS and Javascript. My goal is to enable scrolling through the option list using the up and down arrow keys. However, I have encountered an issue where the scrollbar does not scroll all the way ...

What causes my XMLHttpRequest to be terminated prematurely?

My code utilizes an XMLHttpRequest to log in to a remote server by sending login parameters (username and password) as JSON. Here is my code snippet: var json_data = JSON.stringify({ "method": "login", "user_login": user, "password": password ...

Use ajax, javascript, and php to insert information into a database

Issue at Hand: I am trying to extract the subject name from the admin and store it in the database. Following that, I aim to display the query result on the same webpage without refreshing it using Ajax. However, the current code is yielding incorrect outp ...

Only incorporate the Angular service into the controller when it is necessary

When attempting to incorporate lazy loading for angular services, controllers, directives, and filters, I discovered a way to achieve something similar using RequireJS. However, I am struggling to find a way to dynamically load a service into a controller ...

Navigating through a DOM string in Nuxt.js

I'm in search of a solution to parse a string containing DOM elements within Nuxt.js. The challenge lies in finding a parser that functions seamlessly on both the client and server side. Thus far, I've come across options that are limited to eit ...

Ways to retrieve every span within a string variable that possesses a specific class designation

I'm having trouble listing out all spans with the class "ansspans." There may be one or more span elements with the "ansspans" class, and I need to retrieve them along with their content in order to iterate through them. Can someone explain how to do ...

SlickGrid checkbox formatter/editor experiencing issues with data consistency

Exploring the functionalities of SlickGrid'seditors/formatters, I delved into how these features could potentially alter the data object utilized for constructing the grid (as modifications within the table are usually reflected in the original data o ...

Creating JOIN tables within the create action involves assigning related ids to each table

I am currently working on a room reservation system that involves including options for each room. Data related to the options and their join table, reservation_options, are successfully inserted into the params. However, I am facing an issue with assignin ...

Developing a Customized Modal with Backbone.js

As a newcomer to Backbone, I have been trying to create a Modal in my application by setting up a base Modal class and then extending it for different templates. However, despite conducting some research, I haven't been able to find a solution that fi ...

Looking for assistance with REGEXP to handle a 404 path rendering issue

I am attempting to utilize REGEXP in order to display a 404 page within a react app based on the path, but I am struggling to make it work. This is the specific REGEXP pattern I am trying to achieve: The entire path should not be '/' and should ...

Implementing translation text into a PHP database

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Translate and Save Text</title> </head> <body> <form action="" method="post" name="theform"> <table width="693" border="1" style="table-l ...

Deactivate the form outside of normal business hours

I need to create a form for a delivery service that only operates from 9am to 9pm. If a user submits the form outside of these hours, I want to redirect them to a page displaying the company's operating hours instead of a thank you page. For instance ...

While typing, React-hook-form is removing the input field when the mode property is enabled

Currently, I am implementing a basic form using react-hook-form version 7 along with Material UI. However, I have encountered an unusual behavior when configuring the mode in useForm({mode: ".."}). Below is a snippet of my code: import { yupResol ...

What is the best way to retrieve web pages from the cache and automatically fill in form data when navigating to them from different pages on my website?

On my website, I have multiple pages featuring forms along with breadcrumbs navigation and main navigation. Interestingly enough, the main navigation and breadcrumbs share some similarities. However, my desire is that when users click on breadcrumb links, ...

Struggling to create horizontal buttons for my design

Does anyone have any suggestions for fixing my navigation bar? I attempted to create it myself, but I'm struggling to make everything function properly. https://i.stack.imgur.com/h4yA1.jpg Below are the images of the button in all three states: htt ...

CSS - Update BackgroundColor Depending on Child Element Color

Is there an official CSS way to change the background color based on the child element in HEX? For example: render() { return ( ... <span> <h3 style={{ color: item.color }}>Item Color</h3> </span> ...