Unable to dynamically update properties in CSS and JavaScript without refreshing the page

I've tried applying active properties in my CSS and JavaScript, but it doesn't seem to be working as expected. I can click on each list item, but the active state is not being displayed correctly. Can someone please assist me with this issue? I want it to work seamlessly without having to reload the page.

Here is the HTML code for reference:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/sidebar.css">
</head>
<body>
<div class="sidebar">
    <ul id="menu">
        <li class="list">
            <a href="dashboard.php">
                <span class="icon"><i class="fa fa-tachometer" aria-hidden="true"></i></span>
                <span class="item">Dashboard</span>
            </a>    
        </li>
        <li class="list">
            <a href="sales.php">
                <span class="icon"><i class="fa fa-shopping-cart" aria-hidden="true"></i></span>
                <span class="item">Sales</span>
            </a>
        </li>
        ...
    </ul>
</div>

<script type="text/javascript">

// Function to add active class to clicked button
var header = document.getElementById("menu");
var btns = header.getElementsByClassName("list");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  if (current.length > 0) { 
    current[0].className = current[0].className.replace(" active", "");
  }
  this.className += " active";
  });
}
</script>

</body>
</html>

Here is the CSS code:

@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap');

 .sidebar{
    background: #484848;
    position: fixed;
    top: 52px;
    left: 0px;
    bottom: 20px;
    width: 300px;
    height: 100%;
    box-shadow: 7px 5px 10px black;
}
.sidebar ul{
...
.sidebar ul li a:hover{
    color: black;
    font-weight: bold;
}

Check out the screenshot for a visual representation:

Screenshot: https://i.sstatic.net/nAlQ7.png

Answer №1

For a solution to your problem, utilize the following script:

var header = document.getElementById("menu");
var btns = header.getElementsByClassName("list");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function(event) {
    event.preventDefault(); // Stop the default link behavior
    var current = document.getElementsByClassName("active");
    if (current.length > 0) { 
      current[0].className = current[0].className.replace(" active", "");
    }
    this.className += " active";
  });
}

The specified JavaScript code should be inserted after the <ul id="menu"> element.

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

Ways to determine if a script is currently running within Node.js环境

In my Node.js script, I am importing a separate script that I want to be compatible with various JavaScript engines. Specifically, I only want the line exports.x = y; to run if the code is being executed in a Node.js environment. How can I determine this ...

From HTML to Mat Table: Transforming tables for Angular

I am currently facing a challenge with my HTML table, as it is being populated row by row from local storage using a for loop. I am seeking assistance in converting this into an Angular Material table. Despite trying various suggestions and codes recommend ...

Tips on utilizing media queries to optimize website layout for mobile devices

I'm currently working on a responsive website and utilizing media queries for that purpose. However, I've encountered an issue where the media queries don't seem to apply when the browser window is set to mobile view. Below is the snippet of ...

How to trigger a forced download of a .csv file instead of displaying it in the browser using HTML

After clicking the download button, it should redirect to a new "thank you" webpage and then automatically start downloading a .csv file from the SD card after 2 seconds. However, instead of downloading the file, it is being displayed in the browser. Belo ...

How can we efficiently retrieve newly submitted JSON data using AJAX?

Is there an efficient way for a user to input a number, submit it, and have it update a JSON page without refreshing the entire webpage? Can this be achieved using an ajax call? The code below retrieves game data, but I want it to update when the user su ...

404 error: API endpoint inexistent despite being present

I am encountering an issue while attempting to retrieve a product by its ID. Interestingly, when I tested this using Postman, everything worked flawlessly without any errors. However, when I tried to fetch the data using Angular, it kept returning a 404 no ...

Having issues with the functionality of my radio button in AngularJS

As I delve into Angular and experiment with some code, I am focusing on implementing the following functionality: 1. Depending on the user's preference for adding additional details, they can choose between 'yes' or 'no' using radi ...

Enhancing Your Vue Experience: A Guide to Highlighting and Selecting HTML Elements on Mouse Hover

Incorporating a navigation header using Vue, I utilize v-html to display it seamlessly. Check out the demo - here <section class="text-gray-700 font-heading font-medium relative bg-gray-50 bg-opacity-50"> <nav class="flex justify ...

Leverage ajax/js to dynamically refresh a single select tag within a set of multiple

While working on a project, I encountered a challenge while using JavaScript to update a <select> tag within a page. The specific issue arises because the page is designed in a management style with multiple forms generated dynamically through PHP ba ...

Seeking out all (including potentially relative) URLs on a webpage: Possible strategies to consider

For a coding challenge, I am working on a small python tool to download an entire website locally. In order to view the website offline, I need to convert all URLs to relative URLs. This is necessary to ensure that resource files (such as .js and .css) are ...

Safari on iOS 9 having trouble playing embedded YouTube videos

Recently, I discovered that my YouTube embedded videos are not playing on iOS devices when on my website unless you click in the top left corner of the video. Even after removing all extra YouTube parameters and using standard iFrame embed code, the issue ...

Tips for sending information from PHP to Javascript using jQuery?

I am looking to move data from a PHP page that pulls information from MySQL, with the goal of displaying this data on my mobile app using Cordova. I plan to achieve this using JavaScript. Here is the PHP code I currently have implemented: if($count == ...

Unable to initialize myModule module

An error occurred while trying to instantiate the module 'myModule': [$injector:nomod] Module 'myModule' is not available. Make sure you have spelled the module name correctly and loaded it properly. If you are registering a module, ...

Utilizing Zend JSON encoding for seamless integration with JavaScript

I'm currently working with the Zend Framework. My objective is to pass JSON data from the controller to JavaScript. I have a simple array: $array = array('a' => 1, 'b' => 2); After encoding this array into JSON format: ...

Steps to display selected value on another page

Presented below is the code snippet: <html> <head> <meta charset="UTF-8"/> </head> <body> <!--Text field area starts here--> <H3>My Surveys </H3> <hr> <br> <br> <br> <ol> < ...

Instructions for setting a default value for ng-options when dealing with nested JSON data in AngularJS

I need help setting a default value for my ng-options using ng-init and ng-model with dependent dropdowns. Here is an example of my code: <select id="country" ng-model="statessource" ng-disabled="!type2" ng-options="country for (country, states) in c ...

Handling the width and borders of CSS cells that are positioned outside of a table

Welcome! I recently created a simple gantt organizer as part of a demo. My goal was to make the main table scrollable while keeping certain columns "frozen" for easy visibility when navigating through the data. To achieve this, I followed some advice found ...

Resolving CSS Conflict in Panels with Legacy Bootstrap

I have recently implemented Panels from Bootstrap 3 with the older version of Twitter-Bootstrap. My challenge lies in adding the well class to the panel body, as it results in excessive padding. This was not an issue when using BS3, leading me to believe ...

Efficient code for varying layouts of disabled Angular Material buttons

I've been wondering if there's a simpler way to customize the appearance of a disabled button using Angular Material. Currently, I achieve this by utilizing an ng-container and ng-template. While this method gets the job done, the code is not ve ...

Issue encountered while deploying on vercel: TypeError - Trying to access properties of undefined (specifically 'and')

Encountered this issue during deployment on Vercel. Npm run build did not show any errors. Configuration : "node": "18", "next": "^14.0.0", "next-transpile-modules": "^9.1.0", An error occurred d ...