What is the best way to ensure that all the buttons revert back to their original state when a different button is clicked?

My switch design changes the color of the off button back to its original color when the on button is clicked, and vice versa. But when multiple switches are used within a div, I want clicking the on button of one switch to turn off any other on buttons that were previously clicked. Here is the code I have tried:

$("#darkmodeon, #colorfulon").click(function() {
  $('#responsiveoff').css({
    "background-color": "#d8d8d8",
    "color": "#777777",
    "transition": "all 0.2s ease"
  });
});
#dropdowns > div {
  display: block !important;
}

body {
  margin: 0 auto;
  width: 950px;
  /* border: solid;
    border-color: black; */
  background-color: #f2f2f2;
}

/*--------------Navigation Bar------------*/

#navbar {
  width: 100%;
  background-color: white;
  overflow: auto;
  position: fixed;
  left: 0px;
  top: 0px;
  border-bottom: solid;
  border-width: 1px;
  border-color: #d8d8d8;
  overflow: hidden;
  z-index: 10;
}

#nav-container {
  max-width: 950px;
  min-width: 875px;
  margin: 0 auto;
}

#nav-container h1 {
  float: left;
  margin: 0 auto;
  padding-top: 10px;
  font-family: "calibri light";
  font-size: 25px;
  letter-spacing: 0.3em;
  margin-left: 5px;
  transition: color 0.3s ease;
}

#nav-container a {
  float: right;
  display: block;
  padding: 15px 15px;
  text-decoration: none;
  color: black;
  font-family: "calibri light", sans-serif;
  font-size: 18px;
  transition: background-color 0.5s ease;
}

#nav-container a:hover {
  background-color: #f4f4f4;
  transition: background-color 0.5s ease;
}

#nav-container a:active {
  background-color: #bfbfbf;
}

#nav-container h1:hover {
  color: #aaaaaa;
  transition: color 0.3s ease;
}

#webdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom:...

// The rest of the CSS code is omitted for brevity

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>

// The remaining code has also been truncated for conciseness

Complete JavaScript Function:

$(document).ready(function(){
    
        // Code for hover effects and dropdown animations
        
        // Dark mode switch functionality
    
        var darkon = '#darkmodeon';
        var darkoff = '#darkmodeoff';
        
        // Colorful mode switch functionality
        
        var colorfulon = '#colorfulon';
        var colorfuloff = '#colorfuloff';
    
        // Responsive mode switch functionality
        
        var responson = '#responsiveon';
        var responsoff = '#responsiveoff';

        // Resetting all switches function

        $("#darkmodeon, #colorfulon").click(function() {
            $('#responsiveoff').css({
                "background-color": "#d8d8d8",
                "color": "#777777",
                "transition": "all 0.2s ease"
            });
        });

    });

    

Answer №1

You seem to have a good grasp of jQuery, so I'll share the method that I personally prefer.

My approach would be to add an active class when a button is clicked. However, before adding this class, it's important to first remove the active class from all other elements.

Here is an example of how you can achieve this:

$('#some-id button').click(function () {
    $('#some-id .active').removeClass('active');
    $(this).addClass('active')
});

Next step would be to style the active class with your desired color.

Give it a try and if you still need help, feel free to ask for further assistance.

Answer №2

It would be beneficial to adopt a class-based approach for buttons and utilize data attributes for each theme. This way, you can streamline your code by having just one event listener for all the buttons.

<div class="switchcontainer" data-theme="colorful">
      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>
</div>

The next step is to toggle an active class on the parent switchcontainer when a button is clicked, while simultaneously removing the active class from other containers.

Here's a simplified example:

$('.switchcontainer button').click(function(e) {
  var $btn = $(this),
    isOnBtn = $btn.hasClass('on-btn'),
    $cont = $btn.parent(),
    theme = $cont.data('theme');

  if (isOnBtn) {
    // remove active class from other button groups
    $('.switchcontainer.active').removeClass('active');
    //do something with new theme
    console.log('New theme:', theme)
  }
  // toggle active class on current container
  $cont.toggleClass('active', isOnBtn);
});
.switchcontainer.active .on-btn {
  background: green;
  color: yellow;      
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="switches-container">

  <div class="theme-switch">
    <p class="themename">COLOURFUL MODE</p>
    <div class="switchcontainer" data-theme="colorful">
      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>
    </div>
  </div>

  <div class="theme-switch">
    <p class="themename">RESPONSIVE MODE</p>
    <div class="switchcontainer" data-theme="responsive">
      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>
    </div>
  </div>

</div>

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

What is the best way to align Nav, Title, and Image in a single row?

I am striving to design a navigation bar that appears on both the right and left sides, with the title in between them and an image centered vertically with the text. I have used anchor links within a div for the navigation links, along with unordered list ...

Designing a website's layout with HTML and CSS

I am having trouble developing a concept depicted in the image below. Here is what I have accomplished so far: https://jsfiddle.net/o0zmtr3q/2/. I am struggling to make each box unique, especially with the layout where the text is positioned differently in ...

Tips for arranging headers next to each other on a restaurant menu

I'm currently working on a website for a local restaurant, my very first project of this kind. As I draft the menu section, I'm struggling with displaying Starters and Main Courses side by side on the screen. Additionally, the layout falls apart ...

What is the best way to create an href that points to the parent directory?

I am facing an issue with the HTML page located at the following URL: http://localhost:63343/x/html_pages/http_failures_table/http_failures_table_agg_bl.html The hyperlink is set as: <a href="../http_failures_dict/http_failures_dict_bl_0.txt"> How ...

Chrome does not recognize the inline CSS for linear gradient applied to an HTML.ActionLink button

I attempted to incorporate a gradient background color into my action link button: <p>@Html.ActionLink("Call Cell Phone", "Call", new { id = Model.Id, number = Model.CellNumber }, new { @class = "btn btn-default", @style = "background-color:-webkit- ...

Using Symfony2 with Jquery UI-Tabs for Enhanced User Interface Experience

Whenever I visit the following page, I am able to contact them directly with no issues. http://www.mysite.com/app_dev.php/comments/22 This page contains a basic text form element and a series of comments related to thread 22. I can also submit a new comm ...

Exploring the effective utilization of bootstrap's push and pull functionalities

I've been struggling to rearrange my bootstrap columns for mobile view, but my code just isn't cooperating. It's likely that I'm making a mistake somewhere. Here is the snippet of my code: <div class="container"> <div cla ...

Ways to clear the GET parameters in a MySQL/jQuery ajax request

When performing an ajax call to fetch data from a MySQL database and setting it to run at regular intervals, the question arises about where to store the GET values for clearing purposes. Below is a snippet of code in test.js: var fill = function () { ...

Develop a personalized component featuring various sub-categories

Currently, I am in the process of implementing a data-table element using custom elements (web components). Each row in the table can contain different types of cells such as text, number, date, etc. For example: <my-table> <my-table-cell-te ...

What is the best way to retrieve the responseText using the jQuery.getJSON method within JavaScript?

I am currently facing an issue where I am attempting to retrieve information from a JSON file located in my directory by utilizing the jQuery.getJSON method. Unfortunately, when I try to access the object shown in the image, I am unable to extract the resp ...

Initiate the python script on the client's end

Currently, I am in the process of initiating a Python script designed to parse a CSV file that has been uploaded by the user through the UI. On the client side, how can I effectively trigger the Python script (I have explored using AJAX HTTP requests)? Add ...

Creating a rating system with half-star increments in JavaScript for a five-star scale

Trying to figure out how to create a JavaScript function that can adjust the star rating of an element based on a score using jQuery's addClass and removeClass. I previously had a function for displaying whole stars, but now I am struggling with imple ...

The migration from Bootstrap 4's sticky-top class to thead is a seamless transition

For the past few days, I've noticed that the .sticky-top class is no longer working on thead tags. It was functioning perfectly fine last week, but now it's not responding when I try it on my App. Does anyone know why this might be happening? &l ...

Positioning Text Beside an Image Inside a Bootstrap Grid Column

Just starting out with coding and seeking assistance with a layout inquiry related to bootstrap. I have an image and a paragraph nested within a column in an attempt to utilize the grid system in bootstrap. My goal is to have the image float to the left w ...

Tips for showcasing data in the autocomplete feature

I have implemented the following code to show values: function retrieveValues(input) { var xhttp; if (input.length == 0) { document.getElementById("output").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = functi ...

Arrow for folding HTML elements in Sublime Text

I've noticed that the fold arrow in the gutter doesn't display arrows for all indented elements in HTML, only a select few. Specifically, I've observed that it only shows an arrow on line #2 and #6. This behavior occurs even with reindentin ...

Adjust the width of a div element to a specific size, center the div horizontally, and justify

My issue may be small, but I am struggling to find a solution. I have a content header that is 864px wide with a background image repeated vertically and a footer image. I now have a <div> positioned over the background image and I want it to be 855p ...

Tips for ensuring the accurate retrieval of prop values by waiting for the value to be set

Encountering an issue with the .toUpperCase() method within one of my components, resulting in the following error: TypeError: Cannot read properties of undefined (reading 'toUpperCase') This problem seems to stem from a race condition in fetc ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...

How can we ensure content is aligned to the right when flex-wrap is activated, and distributed evenly with space-between when

I have been searching for a solution to my problem, but I am struggling to articulate my question in a concise manner. So far, I have come up empty-handed. Here is the scenario: When viewed on a large screen, I want the layout to look like this: edge| [C ...