Changing the background color of a button

In the HEADER section, there are 4 buttons (B1, B2, B3, B4), each leading to a different page in the same tab.

The background color of the buttons is set to WHITE.

When a specific button is clicked, the entire page reloads and redirects to the corresponding page for that button.

NOTE: The Header section is present on all 4 button pages.

Now, my requirement is:

Upon clicking a button, only the background color of that specific button should change to another color (for example, RED) while the rest remain WHITE.

For instance, if I click on B1, the page should reload, and the background color of B1 should change to RED while the others stay white.

How can this be achieved using Jquery, Java Script, or CSS?

Please assist me.

.HeaderButtons {
  width: 15%;
  background-color: WHITE;
}
<div id="Header">
  <input type="button" name="B1" id="B1" value="B1" class="HeaderButtons"> 
  <input type="button" name="B2" id="B2" value="B2" class="HeaderButtons"> 
  <input type="button" name="B3" id="B3" value="B3" class="HeaderButtons"> 
  <input type="button" name="B4" id="B4" value="B4" class="HeaderButtons"> 
</div>

Answer №1

If you're looking to dynamically set an active state on a button based on the current URL, you can make use of this modified approach that utilizes buttons instead of links https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/

<div id="Header">
  <input data-href="/" type="button" name="B1" id="B1" value="B1" class="HeaderButtons">&nbsp;
  <input data-href="/page1/" type="button" name="B2" id="B2" value="B2" class="HeaderButtons">&nbsp;
  <input data-href="/page2/" type="button" name="B3" id="B3" value="B3" class="HeaderButtons">&nbsp;
  <input data-href="/page3/" type="button" name="B4" id="B4" value="B4" class="HeaderButtons">&nbsp;
</div>

<script>
   //jQuery script that applies the 'active' class to the button with the corresponding URL path in its data-href attribute 
   $(function() {
      $('input[data-href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
   });
</script>

.HeaderButtons.active {
   background-color: BLUE; //Custom CSS for changing the button color
}

Answer №2

To achieve the best functionality, utilizing AJAX is recommended. Otherwise, if you are refreshing the entire page, it may be necessary to save the clicked button in a session or database (although this is not ideal) or pass it through the URL like page.php?id=b1.

CSS:

.HeaderButtons
{
    width:15%;
    background-color:WHITE;
}
.HeaderButtonsRed {
    background-color:red !important;
}

JS:

$(document).ready(function(){
    $(".HeaderButtons").click(function () {
        if ($(this).hasClass('HeaderButtonsRed')) {
            $(this).removeClass('HeaderButtonsRed');
        } else {
            $(".HeaderButtons").removeClass('HeaderButtonsRed');
            $(this).addClass('HeaderButtonsRed');
        }
    });
});

Answer №3

It seems that achieving a page redirect/refresh without adding parameters to the URL using pure CSS is not possible, as mentioned in previous comments. However, you can explore using cookies as an alternative solution. You can experiment with applying them by utilizing the jQuery cookie plugin.

$('.b1').click(function(){
  var clicks = $(this).data('clicks');
  if(clicks && $.cookie("yourcookiename")=='')
  {
     $.cookie("yourcookiename","yourcookieval");
     // $('.b1').css('background-color','red'); then redirect page code
  }
  else
  {
    // $.removeCookie("yourcookiename"); & then $('.b1').css('background-color','white');
  }
  $(this).data("clicks", !clicks);
});

Answer №4

There are numerous approaches to accomplish this, and the most suitable method will ultimately be based on your specific application, personal preferences, and various other considerations. Some factors to take into account include:

One way to utilize HTML localStorage for storing button IDs on click events is showcased below. This allows you to retrieve the value on subsequent page loads/reloads within the same domain endlessly.

DEMO:

<!DOCTYPE html>
<html>
    <head>
    <style>
        .HeaderButtons {
            width: 15%;
            background-color: WHITE;
        }
    </style>
    </head>
    <body>
        <div id="Header">
            <input type="button" name="B1" id="B1" value="B1" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">&nbsp;           
            <input type="button" name="B2" id="B2" value="B2" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">&nbsp;
            <input type="button" name="B3" id="B3" value="B3" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">&nbsp;
            <input type="button" name="B4" id="B4" value="B4" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">&nbsp;
        </div>
        <script type="text/javascript">
            function setButton(value) {
                localStorage.setItem("buttonID", value);
            }
            if (localStorage.buttonID) {
                document.getElementById(localStorage.buttonID).style.backgroundColor = "RED";
            }
        </script>
    </body>
</html>

Answer №5

Thank you for all your helpful suggestions and responses! I have run into an issue where I do not want any script code to execute on button click because the page will reload upon clicking the button, making it impossible to maintain the background color at that moment.

I did find a solution that is a bit dated, but it serves my purpose perfectly. However, I am open to other solutions if anyone has an alternative approach.

Below is the JQuery/Javascript code that I am currently using:

 $(document).ready(function () 
  { 
   var currentURL=window.location.href;

   if(currentURL.indexOf("Page1.aspx") >-1)
   {
       $('#B1').addClass('ButtonBackColorred');
   }

   if(currentURL.indexOf("{Page2.aspx") >-1)
   {
       $('#B2').addClass('ButtonBackColorred');
   }

   if(currentURL.indexOf("Page3.aspx") >-1)
   {
       $('#B3').addClass('ButtonBackColorred');
   }

   if(currentURL.indexOf("Page4") >-1)
   {
       $('#B4').addClass('ButtonBackColorred');
   }

   $('#B1').click(function()
      {
       window.location=".../Page1.aspx";
    });

$('#B2').click(function()
      {
       window.location=".../Page2.aspx";
    });

$('#B3').click(function()
      {
       window.location=".../Page3.aspx";
    });

$('#B4').click(function()
      {
       window.location=".../Page4.aspx";
    });

});

Answer №6

It's fairly straightforward to implement this jquery snippet for changing a button's background color:

$('#*button id*').css('background-color', '#ff0000');

This code snippet specifically targets the button element to adjust its color.

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

Expanding images to fit the div's width in Bootstrap

I've encountered an issue with my grid of resized images - the original images are larger than what can be accommodated by the Bootstrap grid setup. The problem arises when I decrease the width of my window - instead of maintaining the resized size a ...

Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state. When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here ...

Utilize jQuery to extract information from a webpage and retrieve a JSON object

Looking to extract specific JSON data from a webpage on the same domain that is nested inside a <script> tag with a unique id. <div id="someID"> <script type="text/json" id="scriptID"> { "some more here": "and there", ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

React: Store numerous identical input fields in a single state container

Currently, I have three identical input fields formatted as phone numbers. Each field has its own state and handle method, creating unnecessary repetition in the code. The UI components used are from the Material-UI library, with phone number formatting a ...

Getting unique results from a knex.js INNER JOIN operation

Two tables, metadata and view_events, each have columns for config_id and config_type. The goal is to retrieve all unique view_events based on a user's email address, distinct by config_id and config_type, ordered by timestamp in descending order, lim ...

Guide on submitting a form using a custom AJAX function based on the id or class parameter

Instead of writing an ajax call every time with changing API URL, post method, and form id or class name based on the page, I am attempting to develop a custom function that can manage the API call based on the provided parameters. The essential parameters ...

Navigate to the date selector and select the following month

https://i.sstatic.net/AdWVs.png <button class="mat-calendar-next-button mat-icon-button" mat-icon-button="" type="button" ng-reflect-disabled="false" aria-label="Next month"><span class="mat-button-wrapper"></span><di ...

Discovering the position of an element within an array and leveraging that position to retrieve a corresponding value from a separate array

const STATE = ["TEXAS","CALIFORNIA","FLORIDA","NEW YORK"] const STATE_CODE = ["TX","CA","FL","NY"] With two arrays provided, the first array is displayed in a dropdown menu. The challenge is to retrieve the corresponding state code from the second array ...

Tips for utilizing the output of a pre-defined function within another function in SASS

How can I effectively utilize the outcome of darken( $var, 10% ) in the SASS function oppositeColor( $darkenedColor )? The code I am working with currently looks like this: $color1: #000000 !default; $color2: darken( $color1, 5% ) !default; $color3: oppos ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

The Angular web application utilizing an ASP.NET Web API that is hosted on AppHarbor is showing the incorrect webpage

Working on a web application using Angular and ASP.NET Web API in Visual Studio 2015 has been quite the journey for me. Upon running the solution in VS2015, I encountered two tabs opening in Chrome - one for my Angular client-side application and another ...

Does Sublime Text 2 offer intelligent intellisense with jQuery suggestions that are not just snippets?

Is there a way to achieve the same level of detailed assistance in my lightweight Sublime Text 2 as I do with vs2012? Most packages I've tried focus on snippets rather than providing smart hints. In vs2012, I used -vsdoc to solve this issue. How can I ...

Creating a Future Prediction Graph with ECharts

I am looking to create a forecast chart that includes both Actual values (presented as a line chart) and projected values (displayed as a dotted chart). An example of what I have in mind can be seen here, created using Excel: https://i.sstatic.net/q18An.pn ...

JavaScript guide: Deleting query string arrays from a URL

Currently facing an issue when trying to remove query string arrays from the URL. The URL in question looks like this - In Chrome, it appears as follows - Var url = "http://mywebsite.com/innovation?agenda%5B%5D=4995&agenda%5B%5D=4993#ideaResult"; ...

How does one make sense of comparing integers with strings and arrays?

I was experimenting with the == operator in Javascript, and the results were intriguing: 0 == "0" // true and then 0 == [0] // true BUT: "0" == [] // false It's quite perplexing for someone unfamiliar with Javascript like me. I also observed: ...

jQuery providing incorrect measurements for an element's height

I am encountering an issue with obtaining the height of the #header element in my AngularJS application. Despite using jQuery, the returned height seems to be incorrect. The current code snippet looks like this: $(document).ready(function() { function ...

Trouble arises when attempting to incorporate the Restangular dependency with Angular using browserify

I've been using browserify to manage my angular dependencies successfully, however, when I try to add restangular I encounter an error: "Uncaught Error [$injector:modulerr]". Here's a glimpse of my package.json: "browser": { "angular": "./ ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

The functionality for validating and submitting forms using Ajax is not functioning as expected

My input field validation is functioning properly, but I am having trouble with the ajax submission. Can anyone help me find the bug in my jQuery code snippet? $(document).ready(function() { $("#eValidate").live("click", function() { if (!Valida ...