Switching classes based on the click of a link

I have a navbar that looks like this: https://i.sstatic.net/1jcRr.png

Below is the relevant HTML code for the navbar:

        <div class = "navbar">
            <a class = "active" href ="{% url 'keiji-home' %}">home</a>
            <a href ="#" onclick = "makeActiveLink('communities-tag')"
            id="communities-tag">
                communities
            </a>
            <a href = "#">feeling lucky</a>
            <a href = "{% url 'keiji-about' %}">about</a>
            <div class = "navbar--right">
                <a href = "{% url 'register' %}">login/signup</a>
            </div>
            
        </div>

My goal is to have a red background (class = "active") on the link (such as "home", "communities", "feeling lucky", etc.) when I am on that specific page. For example, if I'm on the "about" page, the red background should be on the about link.

As someone who is new to JavaScript, here is what I've attempted so far after researching other questions:

    function makeActiveLink(id)
    {
        var selectedLink = document.getElementById(id);
        selectedLink.classList.className += "active";
    }

And then on the link, for instance, "communities":

<a href ="#" onclick = "makeActiveLink('communities-tag')"
            id="communities-tag">

However, my current approach is not yielding the desired result.

In addition, I would like the "active" class to be removed from the previous link. In other words, when transitioning from the "home" page to the "about" page, the class should be removed from "home" and added to "about".

Although I'm unsure if this information is relevant, I am using Django (which I'm also new to) to operate this website.

Answer №1

Here is a potential solution for what you are trying to accomplish:

function activateNavLink(element) {
    var navLinks = document.getElementsByName("nav");
    navLinks.forEach(function(link) { link.classList.remove("active"); });
    element.classList.add("active");
}

Then in your HTML:

<a href="#" onclick="activateNavLink(this)" name="nav">Home</a>
<a href="#" onclick="activateNavLink(this)" name="nav">Communities</a>
...

Answer №2

selectedLink.classList.className += "active"
; Remove the "+"

When selecting the link for "Home," assign a class name of "active done." Then, in the CSS, include .done {background: ...(your color)} and use JavaScript to update the class in your function.

I hope this explanation is helpful to you.

Answer №3

element.classList.className is considered incorrect because they are not the same thing.

To make it work properly, you can use the following code:

function activateLink(id) {
  //Remove 'active' from previous link
  var oldLink = document.getElementByClassName("active")[0];
  oldLink.classList.remove("active");
  //Add 'active' to new link
  var selectedLink = document.getElementById(id);
  selectedLink.classList.add("active");
}

getElementByClassName() looks for elements with a specific class and returns a collection of elements, which is why we use [0] at the end.

Just be aware that this means you should not use the class active elsewhere on the page. If this is a problem, consider renaming it to something like active-nav.

Additionally, it's recommended to include all your code (including html) in a snippet for easier troubleshooting.

Answer №4

in a simple way:

  <div class="navbar">
    <a class="active" href="{% url 'keiji-home' %}">home</a>
    <a href="#" > communities </a>
    <a href="#">feeling lucky</a>
    <a href="{% url 'keiji-about' %}">about</a>
    <div class="navbar--right"> <a href="{% url 'register' %}">login/signup</a>
  </div>
document.querySelectorAll('div.navbar > a').forEach((lnk,_,A)=>
  {
  lnk.onclick=_=>A.forEach(a=>a.classList.toggle('active',(a===lnk)))
  })

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

Tips on ensuring that a span element is positioned at the bottom of a table cell

Is there a way to position the span element at the bottom of a table cell in HTML: Here is the code snippet I'm working with: <td> <span class='cat-otsikko'>Product title</span> <span class='cat-hinta&apos ...

What is the best way to adjust the font weight of a Bootstrap 4 modal header?

Is there a way to adjust the font weight in the header of a Bootstrap 4 modal? As an added challenge, I'm also interested in changing the font color to #7f7f7f... <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" r ...

JavaScript: The function is encountering issues with properly formatting the numbers

I am currently facing an issue with a function I have created to format numbers for currency by inserting commas every 4 digits. The problem lies in the fact that the first 4 numbers do not have a comma added where it should be, and the formatting only wor ...

Is there a way to asynchronously load multiple textures in three.js using a callback function?

Bringing in a single texture with a callback is a simple task, for instance: var loader = new THREE.TextureLoader(); var texture1 = loader.load("https://i.imgur.com/UiTMJzv.png", process); //executed only once texture1 is loaded function process(){ } B ...

The functionality of the button is currently not compatible with Internet Explorer

I have encountered an issue in my application involving a combination of <h:outputLink> and <p:commandButton> as shown below: <h:outputLink target="_blank" value="theURL"> <p:commandButton value="Click" type="button" /> </h: ...

What is the purpose of running "npm install" if the "node_modules" directory already exists?

When "npm install" is run on a project directory containing both a "package.json" file and a "node_modules" directory, what impact does it have? Does it replace the current modules with newer versions? Does it update them, or does it have no effect at all ...

Incorporating JavaScript into Tailored Widgets

This question pertains to Django: Best Way to Add Javascript to Custom Widgets However, this is a different scenario. The original inquiry focuses on incorporating javascript into a custom django widget using forms.Media, but that approach does not appl ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

How to Incorporate an Error Function into XPages Partial Refresh Events (dojo.xhrPost)?

I have a page that relies on multiple partial refreshes for user interaction. Rather than implementing a session keep alive mechanism, I am interested in detecting error responses from these partial refreshes to alert the user of their expired session or t ...

html and css code to create a linebreak ↵

I received a JSON response from the server, and within this data is a "return line" in the text. {text: "I appear in the first line ↵ and I appear in the second line"} However, when I try to display this on an HTML page, the "return line" does not show ...

The function .then is not compatible with AngularJS

I have a service that is responsible for loading data. angular.module('App').service('daysService', ['$http','$q',function($http,$q) { var days = []; return { loadDay: function() { ...

How can I automatically increase a field when editing a row in JqGrid for PHP?

While using JqSuite for PHP, I am attempting to automatically increment a field value every time I submit a row edit. However, my code doesn't seem to be working as expected! Snippet from grid.php: $custom = <<<CUSTOM var rowId; var keys, ...

Is there a way to create a textbox input that provides autocomplete/autosuggest but displays only the first match directly within the textbox instead of showing a list?

While I came across several autocomplete/autosuggest samples, none of them quite fit what I'm looking for. Instead of displaying a list below the textbox that requires clicking or selecting, I want to show the closest match inside the textbox itself a ...

Performing a callback function in node environment

It's common knowledge that Node.js operates on a single thread and relies on asynchronous operations for I/O tasks. When Node.js is not actively running code, it actively listens for events using platform-native APIs that allow it to respond to eve ...

Why are the links in the navgoco slide menu failing to function properly?

I utilized a demo from jQueryRain to create a collapsible menu using jQuery. However, after completion, I discovered that none of the links were functioning properly. Upon visiting the documentation page, I noticed that many users were encountering the sam ...

HTML tag naming can vary in different array types

When working on a project, I came across the need to clone input elements. After searching online, I found various ways to achieve this. One method involved creating an HTML input array with different naming conventions depending on the source. For example ...

Is it possible to vertically align variable length text within a container of fixed height?

One common method for centering text inside a div is to use the following CSS trick: .center-div { display:table-cell; vertical-align: middle; } The issue arises when the text within the div varies in length and I require the container to have fi ...

Is there a way to transfer driver information between methods smoothly?

Just started working with Selenium and I have a query. I created a method called urlload to load a specific URL, but when I try to read webElements of the webpage loaded in that method from another class, it doesn't seem to work. Any advice or hel ...

Attempting to divide the main page into quadrants

I want to split my homepage into four equal images without any scrolling. When you click on the website, I want the four images to expand and cover the entire screen with no scrollbars. I've made some progress with my code, but it's not quite the ...

Changing fonts for languages that are read from right to left in WordPress

I am currently working on a WordPress site that features posts in both English and Urdu. The English posts are written from left to right (ltr), while the Urdu posts are written from right to left (rtl). When I submit post data in the wp editor, it publish ...