Altering the background color of a button in a navigation bar and mirroring that same color on a linked page when clicked

I'm facing an issue with my asp.net Master page. I have a menu bar with 4 buttons, and I want to change the color when a button is clicked. I was able to achieve this using java script, but the problem arises when I redirect to a child page, as the color changes back to its initial state.

Here is the ASP.NET CODE (each button has different colors for class and focus):


    <div>
        <input type="button" id="t1" class="button" onclick="setColor('tab1', 0)" value="b 1">
        <input type="button" id="t2" class="button" onclick="setColor('tab2', 1)" value="b 2">
        <input type="button" id="t3" class="button" onclick="setColor('tab3', 2)" value="b 3">
    </div>

Below is the java script code:


function setColor(pos) {
    var buttons = Array.prototype.slice.call(document.querySelectorAll(".button"));

    buttons.forEach(function (btn) {
        btn.addEventListener("click", function () {
            if (this.value == "button 1") {
                window.location.href = "Default.aspx";
            } else if (this.value == "button 2") {
                window.location.href = "Default2.aspx";
            } else if (this.value == "button 3") {
                window.location.href = "Default3.aspx";
            }

            buttons.forEach(function (btn) { btn.classList.remove("focus"); });

            this.classList.add("focus");
        });
    });
}

Answer №1

To implement the following functionality, you need to insert this code into the Master page:

 $( document ).ready(function() {

    var path = window.location.pathname;
    var page = path.split("/").pop();

    var tab1 = document.getElementById("tab1");
    var tab2 = document.getElementById("tab2");
    var tab3 = document.getElementById("tab3");

    tab1.classList.remove("active");
    tab2.classList.remove("active");
    tab3.classList.remove("active");

     switch(page) {
            case 'Home.aspx':
                tab1.classList.add("active");
                break;
            case 'Products.aspx':
                tab2.classList.add("active");
                break;
            case 'Contact.aspx':
                tab3.classList.add("active");
                break;
        }

    });

Answer №2

When you're redirecting the page and reloading both the html and the css, everything reverts back to its original state, causing you to lose any color changes you made. However, a solution is to check the filename when the page loads and then set the button's color accordingly. Here's an example:

document.onload = function() {
    var pathName = window.location.pathname.split('/');
    var fileName = pathName[pathName.length - 1]; 

    switch(fileName) {
        case 'Default.aspx':
            document.getElementById('t1').classList.add("focus");
            break;
        case 'Default2.aspx':
            document.getElementById('t2').classList.add("focus");
            break;
        case 'Default3.aspx':
            document.getElementById('t3').classList.add("focus");
            break;
    }
}

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

Guide to substituting the index value with the user's specific choice

Let's simplify this. Suppose I have a list in my ng-repeat 1. A & index[0]<br> 2. B & index[1]<br> 3. C & index[2]<br> 4. D & index[3]<br><br> and there is an input field where the user can priorit ...

Guide to creating a simple multi-column index linking each item to a specific page reference

Here's an idea I have in mind: Alan 12 | Byron 104 Alfred 54 | Charles 33 Ann 28 | Cleopatra 7 Basil 133 | Corey 199 ...

Ways to verify if a specific extjs panel has finished loading

After a specific panel has finished loading, I need to insert a JavaScript code (using the panel's ID). What is the best way to ensure that the panel has been fully rendered so that I can access its ID using document.getElementById? Thank you. ...

I'm perplexed as to why my webpage displays differently across various browsers

Currently, I am utilizing the Yahoo CSS reset and all my CSS is based on pixel values rather than relative units like ems. Interestingly, there seems to be a discrepancy in the position of the bottom right corner of the form-containing div between Chrome a ...

Tips for retrieving data from Angular dropdown menus

How to Retrieve Selected Value in AngularJS HTML <select data-ng-model='datasource.value' ng-options='sourcetype.dataSourceType as sourcetype.dataSourceDesc for sourcetype in sourcetypes' data-ng-change="getAccountCredentials(sourc ...

What steps can be taken to avoid or halt focusing on the following input text element?

I came across a situation where I have to focus on the h1 element of an overlay instead of moving to the next tabbable element. The overlay appears after a service call triggered by blur event from the first input text field. Every time the blur event is ...

Having trouble retrieving a value from a .JSON file (likely related to a path issue)

My React component is connected to an API that returns data: class Item extends Component { constructor(props) { super(props); this.state = { output: {} } } componentDidMount() { fetch('http://localhost:3005/products/157963') ...

Create a simulated constructor to generate an error

Currently, I am faced with a challenge of writing a test that is expected to fail when trying to instantiate the S3Client object. It seems like Vitest (similar to Jest) replaces the constructor with its own version when mocked, preventing my original const ...

Exploring the Window.prompt() method in JavaScript

Take a look at this code snippet: <!DOCTYPE html> <html> <body> <p>Click the button to show the prompt box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> funct ...

How can I incorporate multiple JSX files into plain HTML without using npm?

I have a question regarding importing JSX files in an HTML file without using npm and directly running it with LiveServer. I have two files, index.js and app.jsx, that I want to connect within my index.html script. How can I achieve this? Code: index.html ...

implementing a webpage enhancement that enables loading content asynchronously

I find myself puzzled. Lately, I've delved into learning Spring MVC through the development of a web application designed to display live sports scores in real-time. The core functionalities are already in place, but I'm unsure about how to creat ...

Choose all of the IDs from various sections using Jquery

I am facing an issue with having 2 identical IDs inside 2 separate sections. When the button is clicked, I want it to select the ID within this section and apply a style, then also select the ID in the other section and apply that same style. The code sni ...

The for each loop fails to return the value

In my Vue component, I have a conditional loop that iterates through train stations with 'New York' as the destination or on the route. <tr v-for="departure in filterTrainStations" :key="departure.name"> <td>{{ departure. ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...

Implementing a button callback function using Aurelia binding

Is there a way to pass an array of custom button objects to a specific element? Here's an example: <my-component header="My Title" buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]"> </my-component> ...

Discovering time overlaps with Javascript and moment.js

In my calendar project, I am storing events for a day in an array. The start and end times are stored as String values in the following format: Example of events in a day const events = [{ "_id": "5bdf91a78197f0ced6c03496", "user": "5bd62237d6 ...

Exploring the ways to center align text using bootstrap

I used Twitter Bootstrap to arrange text and image side by side, but I'm having trouble centering the text. Do you have any ideas on how to achieve this? <div class="row"> <div class="col-sm-1"> <a href="ghfhg"><i cla ...

Navigate to the element by clicking on the link, then apply a class to that specific element

I'm currently working with this HTML code: <div id="main"> <p>some text</p> <a id="goto-notes" href="#">see notes</a> <p>some text...</p> <div id="notes"> <p>notes here< ...

What is the process for requesting a specific condition using jscript and jquery?

I'm experimenting with the following code: while (true) { $(document).ready(function() { setInterval(function () { if ($("h2").text() == "What is a light-year?") { $("#choice2").delay(200).queue ...

Vue: Displayed list displaying checked checkboxes

My attempt at displaying the selected checkboxes is as follows: <pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre> <ul class="list-unstyled" v-for="category in categories" ...