What is the best way to ensure that an element remains active even after a page refresh?

I have been using this code to activate the current element, which I came across on a website called "w3schools.com". However, whenever I refresh the page, the currently active element disappears. Is there a way to ensure that the active element remains highlighted even after a page refresh?

// This code snippet adds the 'active' class to the current button (highlighting it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
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";
  });
}
/* Button styling */

.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}


/* Styling for the active class and hover effects */

.active,
.btn:hover {
  background-color: #666;
  color: white;
}
<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>

<div id="myDIV">
  <button class="btn">1</button>
  <button class="btn active">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="btn">5</button>
</div>

Answer №1

Issue resolved, here is the solution

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Styling for buttons */
.btn {
border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
font-size: 18px;
}

/* Styling for active class and mouse-over effects */
.active, .btn:hover {
background-color: #666;
color: white;
}
</style>
</head>
<body>

<h1>Active Button</h1>
<p>Highlight the currently active button.</p>

<div id="myDIV">
<button class="btn">1</button>
<button class="btn active">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
</div>

<script>


 var header = document.getElementById("myDIV");
 var btns = header.getElementsByClassName("btn");

for (var i = 0; i < btns.length; i++) {
     btns[i].addEventListener('click', function(e){
        var current = document.getElementsByClassName("active");
        current[0].classList.remove('active');
        this.classList.add('active');
        var array = [];
        array.push(btns);
        localStorage.setItem('selectedElement', this.innerText);
     });
}

    function setActivatedItem(){
        var item = localStorage.getItem('selectedElement');

        if(item){
            for (var a = 0; a < btns.length; a++) {
                if(btns[a].innerText == item){
                    btns[a].classList.add('active');
                }else{
                    btns[a].classList.remove('active');
                }
            }
        }
    }

    window.onload == setActivatedItem();

</script>

</body>
</html>

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

Having divs stacked on top of each other with one positioned fixed and the other

In my HTML document, there is a main div element called container that contains several child elements also in the form of divs. One specific child div, named top_bar, has its positioning set to fixed, while the rest of the child divs have relative posit ...

How to modify the link to ensure that a particular tab is already selected when the page loads

How to Add Script for Linking to Rawdata Tab I need help loading specific page content with the Rawdata tab open instead of the Summary tab. What code should I add to the link to ensure that the page loads with "Rawdata"? https://i.stack.imgur.com/avETs. ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

Tips for rotating and positioning an element in the top left or top right corner of a page

I recently tried rotating a div with text and wanted to position it at the top left corner. I was able to successfully align it at the top, but I'm having trouble getting it to align with the left edge. Any tips on how to achieve this? .credit { ...

Creating an effective Google Login Button in a React application

Struggling to implement a Login/Sign In Google Button on my page using react, I'm new to this framework and it's just not working as expected. Following tutorials from the internet but still facing issues. To summarize, I'm utilizing tailw ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...

Steps to transfer text from one input field to another by clicking a button using JavaScript

Hello, I am new to Javascript so please forgive me if my question seems silly. I have been tasked with creating a form containing two input fields and a button. When the button is clicked, the text entered in the first field should move to the second field ...

Conceal a section of a container with the click of a button within a WordPress Plugin

I am currently utilizing a Wordpress plugin known as contact form 7 to construct an email list for an upcoming website project. The client has specifically requested that we avoid using services like mailchimp due to their preference of not sending ANY ema ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

Parse a string in the format of "1-10" to extract the numbers and generate an array containing the sequence of numbers within the range

Looking to convert a string in the format "1-10" into an array containing the numbers within that range. Display the array on the screen using a for loop. For example, if "1-5" is provided, the resulting array should be: {1, 2, 3, 4, 5} Create a workflow ...

The event on the full calendar is stuck in place and will not budge

function moveEvent(event, delta, revertFunc) { console.log(event.title + " has been moved to " + event.start.format()); var page = '../include/UpdateCalendarEvent.php'; $("#dialog") .data('start', event.start.format ...

Tips for including vue-autonumeric in your webpack 2 setup

Encountering a problem while bundling the vue-autonumeric package with Webpack 2, where the dependency AutoNumeric is not being found properly. Although there is an alias set up in the configuration that works fine with webpack 3, it seems to fail when wo ...

Tips for making radio button selection mandatory in an HTML5 form

How can I require a user to select one radio button in an HTML 5 form before submitting it? I attempted to use the required attribute, but since there is no radio button group, how can I apply this requirement? <form action="/Home/Sendtitle" method=" ...

What is the best way to create height segments from a cylinder in three.js?

My current project involves a cylinder that is divided into multiple height segments, with the number of segments depending on the specific data. Each height segment contains a value that I want to use for extruding the entire circle at that particular hei ...

Discovering the specific marker that was clicked from a group of Google map markers

I have a collection of marker objects named markers. I am currently utilizing a for loop to assign event listeners to each one. However, I am encountering difficulty in determining which specific marker was clicked. This is the current code snippet I have ...

Tips for altering the color of a specific row in JQuery by targeting its unique id

I've been struggling to accomplish a simple task using Jquery and CSS, but I seem to be stuck. My issue involves making an ajax request to update a PostgreSQL table and retrieve an id in return. This id corresponds to the id of a row in a previously ...

Adjust the dimensions of the text area to modify its height and width

Can someone help me adjust the width and height of the <textarea> tag in HTML so that it only has two lines (rows)? Right now, it's only displaying one line. Any suggestions on how to solve this issue? Even when I try changing the width to 1000 ...

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...

What is the best way to set the width of an element to 100% while accounting for padding

My dilemma involves an HTML input field. The input currently has padding: 5px 10px;, but I need it to occupy 100% of its parent div's width (which is fluid). If I try using width: 100%;, the input ends up being wider than intended due to the padding ...