Switching the background image upon clicking a navigation item in CSS

Is there a way to change the background color of this nav element when it is active/clicked using CSS?

    <div class="row container-fluid mainTabCon" style="width: 100%" style="">
      <ul class="nav nav-pills" style="margin: 0 auto; ">
         <li class="nav-item">
            <a class="nav-link active" data-toggle="pill" href="#"><strong>GENERALIDADES</strong></a>
         </li>
         <li class="nav-item">
            <a class="nav-link" data-toggle="pill" href="#"><strong>DESEMPEÑO</strong></a>
         </li>
      </ul>
    </div>

Any assistance on how to achieve this would be greatly appreciated.

Answer №1

Insert the following script at the end of your body section or script file: (modified version of code from w3 schools)

// Locate the container element
var btnContainer = document.getElementById("myDiv");

// Find all buttons with class="btn" within the container
var lis = btnContainer.getElementsByClassName("nav-link");

// Iterate through the buttons and assign the active class to the current/clicked button
for (var i = 0; i < lis.length; i++) {
    lis[i].addEventListener("click", function() {
        var current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
    });
}

Then proceed to customize the .active class:

.active {
    background-color: blue;
}

Complete page layout with described code:

 <!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style type="text/css">
    .active {
        background-color: blue;
    }
</style>
<body>
    <div class="row container-fluid mainTabCon" id="myDiv" style="width: 100%" style="">
        <ul class="nav nav-pills" style="margin: 0 auto; ">
            <li class="nav-item">
                <a class="nav-link active" data-toggle="pill" href="#"><strong>GENERALIDADES</strong></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-toggle="pill" href="#"><strong>DESEMPEÑO</strong></a>
            </li>
        </ul>
    </div>

    <script>
    // Locate the container element
    var btnContainer = document.getElementById("myDiv");

    // Find all buttons with class="btn" within the container
    var lis = btnContainer.getElementsByClassName("nav-link");

    // Iterate through the buttons and assign the active class to the current/clicked button
    for (var i = 0; i < lis.length; i++) {
        lis[i].addEventListener("click", function() {
            var current = document.getElementsByClassName("active");
            current[0].className = current[0].className.replace(" active", "");
            this.className += " active";
        });
    }
</script>
</body>
</html>

If Bootstrap's js libraries are required, include them at the end of the body section and test without the above code to see if it functions properly.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

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

How to create a full-screen 2x2 grid layout using divs in HTML

I am attempting to create a grid layout of 4 divs arranged in a 2x2 configuration. I would like to have a 1 pixel border between these divs, similar to the following structure: 1|2 -+- 3|4 Each div should have equal size and collectively fill the entire ...

jQuery's slide toggle function is limited to toggling the visibility of just one section at

Welcome to my first post! As a newbie in web development, I have just started my first project. While I feel comfortable with HTML and CSS, jQuery is proving to be a bit challenging for me. In the head section of my intranet page, I have the following cod ...

Using React Native to create a concise text component that fits perfectly within a flexbox with a

Within a row, there are two views with flex: 1 containing text. <View style={{ flexDirection: "row", padding: 5 }}> <View style={{ flex: 1 }}> <Text>Just a reallyyyyyyyy longgggg text</Text> </View> ...

CSS for a Dropdown Menu with Multiple Layers

I've successfully implemented a dropdown menu, but now I'm facing the challenge of adding another level to it. Specifically, I want a second level to drop down when hovering over "Test3". What do I need to add or modify in the code to achieve thi ...

The jQuery method .index() can be quite perplexing when it comes to

http://learn.jquery.com/using-jquery-core/understanding-index/ After reading the article linked above, I found myself struggling to grasp the reasoning behind why the index number changes in a peculiar manner when an argument is used with .index(). Consi ...

Troubleshooting problem with media queries in CSS

As a newbie to HTML and CSS, I've been encountering difficulties with media queries. My website seems to only function properly when viewed in a resolution of 1920x1080, so I attempted to implement some media queries in my CSS to cater to other resolu ...

Is it possible to implement a code that will organize a dropdown list alphabetically?

Could someone assist me in sorting the location items alphabetically in this search form at: I would like the locations to be displayed in alphabetical order. Any help with updating the code below would be greatly appreciated. Here is the current code sn ...

PHP child categories causing jQuery menu loading issue

Our custom jQuery menu has been functioning perfectly on our OpenCart store. However, we are facing an issue where the 2nd level child categories are not being displayed. It seems that there is an error in the PHP code for both the modified and original me ...

Tips for printing a page to match its on-screen appearance

I am in the process of developing a scheduling page within ASP.NET Web Forms, incorporating custom CSS. I have successfully added a print button, but when I try to print the page, the CSS styles are not being applied. How can I resolve this issue? This is ...

Is there a way to prevent wrapping in a column, causing the last column to partially extend outside the container when the first column is hovered over?

Is there a way to prevent wrapping of a column so that when I hover over the first column, the last column displays half out of the container? I attempted to achieve this by setting the 25% to flex: 0 0 50%; in my column when hovering on the box-hover cla ...

flexbox layout with a fixed sidebar that stays in place

Is there a way to make the sidebars in the holy grail layout sticky using flexbox? Specifically, I want the aside and nav sections of the HTML to stop scrolling down further once the last element is reached. I've tried various methods but with limited ...

Selenium webdriver unable to locate an empty element

I'm currently trying to find a specific element using selenium webdriver: <div class="lv-product__details"><div class="lv-product__details-head"><span class="lv-product__details-sku"> M40712 ...

Exploring the Terrain: Troubleshooting Meteor CSS with Twitter Bootstrap

Recently, I have encountered an issue that perplexes me - I am unable to debug less code in my meteor app when the twbs:boostrap package is present. Interestingly, everything works fine when I remove it, but as soon as I add it back, the CSS seems to be co ...

Looking to temporarily hide a transparent div while the page is loading, and then reveal it once the page has finished loading?

Hey, I've created a code for a transparent div that I'm using behind some text on the homepage of a website to make the text more prominent: #transdiv { position:absolute; top:228px; width:852px; height:160px; background-colo ...

Occasions focused on the <input type="file"> feature

Looking for a way to write a file input in React that accepts CSV files, validates them, and prevents upload if there are errors? Check out the code snippet below: <CustomInput type="file" id="fileBrowser" name="file" label={filename || 'Choos ...

Clone content upon pressing the Enter key

I am facing an issue with my editable container where I have a div inside it. Whenever I press enter, the div duplicates, resulting in two divs stacked on top of each other. The container has contenteditable set to true, which might be causing this problem ...

jsoup - locate element and delete it along with the element preceding it

In my Android app, I am working on extracting data from a stock market historical prices table. However, there are certain rows in the table that need to be removed for clarity. Specifically, I am trying to remove a row in the third tr. I have managed to r ...

I am currently attempting to generate a chart that displays information on countries utilizing the restcountries API. Despite being a beginner in this area, I have encountered some challenges and am seeking guidance

I'm struggling to display detailed information for each country separately. Whenever I try to loop through the data, all the contents end up getting merged into a single cell. What can I do to achieve the desired result? https://i.stack.imgur.com/dZS ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

Using the val() function on a select element can occasionally result in a null value

Having an issue with my select. For some reason, when I use $(".test").val(), it sporadically returns null. Can't seem to figure out what's causing this inconsistency. console.log($('.test').val()); <script src="https://ajax.googl ...