What is the best way to create a Div element that functions as a button, becoming active when clicked while deactivating all other Div elements

function toggleButton1() {
  $("#button1").toggleClass("button-active button-inactive");
  $("#button2").toggleClass("button-inactive button-active");
  $("#button3").toggleClass("button-inactive button-active");

}

function toggleButton2() {

  $("#button2").toggleClass("button-active button-inactive");
  $("#button1").toggleClass("button-inactive button-active");
  $("#button3").toggleClass("button-inactive button-active");

}

function toggleButton3() {

  $("#button3").toggleClass("button-active button-inactive");
  $("#button2").toggleClass("button-inactive button-active");
  $("#button1").toggleClass("button-inactive button-active");

}
.button-active {
  display: inline-block;
  border: 1px solid #CCC;
  background-color: white;
  box-shadow: 0px 0px 4px rgb(130, 130, 130) !important;
  cursor: pointer;
  vertical-align: middle;
  max-width: 100%;
  padding: 16px;
  text-align: center;
  border-radius: 4px;
  color: rgb(130, 130, 130) !important; }

.button-inactive {
  display: inline-block;
  border: 1px solid #CCC;
  background-color: #e7f6fe;
  box-shadow: 0px 0px 4px rgb(130, 130, 130) !important;
  cursor: pointer;
  vertical-align: middle;
  max-width: 100%;
  padding: 16px;
  text-align: center;
  border-radius: 4px;
  color: rgb(130, 130, 130) !important; }

.button-hover {
  color: rgb(130, 130, 130) !important;
  background-color: #e7f6fe;
  box-shadow: 0px 0px 4px rgb(130, 130, 130) !important;
  border-radius: 8px;
  margin-right: 0px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
  <div class="row">
    <div class="col-md-4 button-active" id="button1" onclick="toggleButton1()">
      <div class="col-12">Update 1</div>
    </div>
    <div class="col-md-4 button-active" id="button2" onclick="toggleButton2()">
      <div class="col-12">Update 2 </div>
    </div>
    <div class="col-md-4 button-active" id="button3" onclick="toggleButton3()">
      <div class="col-12">Update 3 </div>
    </div>
  </div>

</div>

Hello, I have created these div buttons that should act as individual selectable options with different colors for each when active.

  1. Clicking one button will activate it and deactivate the others.

  2. When a button is activated, its background color should change to blue.

  3. The hover effect color should be consistent with the selected color.

  4. I have used JavaScript toggling functions for this functionality, but encountered an issue where only one button can be toggled at a time:

    (function toggleButton1() { $("#button1").toggleClass("button-active button-inactive");)}

    The above JavaScript function works correctly for a single button, but applying it to other buttons selects all of them on click. Please assist me with this. Thank you.

Answer №1

Let me share a simpler solution to the issue of moving the active class using just a single script code.

Here is the code snippet for your problem:

$(document).ready(function() {
  $('.divbtnbg').click(function() {
    $('.divbtnbg').removeClass('active');
    $(this).addClass('active');
  });
});
.divbtnbg {
  display: inline-block;
  border: 1px solid #CCC;
  background-color: white;
  box-shadow: 0px 0px 4px rgb(130, 130, 130) !important;
  cursor: pointer;
  vertical-align: middle;
  max-width: 100%;
  padding: 16px;
  text-align: center;
  border-radius: 4px;
  color: rgb(130, 130, 130) !important;
}

.divbtnbg.active,
.divbtnbg:hover {
  color: rgb(130, 130, 130) !important;
  background-color: #e7f6fe;
  box-shadow: 0px 0px 4px rgb(130, 130, 130) !important;
  border-radius: 8px;
  margin-right: 0px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-md-4 divbtnbg" id="b1">
        <div class="col-12">Update 1</div>
      </div>
      <div class="col-md-4 divbtnbg" id="b2">
        <div class="col-12">Update 2 </div>
      </div>
      <div class="col-md-4 divbtnbg" id="b3">
        <div class="col-12">Update 3 </div>
      </div>
    </div>
  </div>
</body>

</html>

Answer №2

Only a slight modification needs to be implemented

$(".menu > div").click(function(){
  $(".menu > div.selected").removeClass("selected");
  $(this).addClass("selected")
})
.divbtnbg {
  display: inline-block;
  border: 1px solid #CCC;
  background-color: white;
  box-shadow: 0px 0px 4px rgb(130, 130, 130) !important;
  cursor: pointer;
  vertical-align: middle;
  max-width: 100%;
  padding: 16px;
  text-align: center;
  border-radius: 4px;
  color: rgb(130, 130, 130) !important;
}

.divbtnbg:hover, .selected {
  color: rgb(130, 130, 130) !important;
  background-color: #e7f6fe;
  box-shadow: 0px 0px 4px rgb(130, 130, 130) !important;
  border-radius: 8px;
  margin-right: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12">
  <div class="row menu">
    <div class="col-md-4 divbtnbg" id="b1">
      <div class="col-12">Update 1</div>
    </div>
    <div class="col-md-4 divbtnbg" id="b2">
      <div class="col-12">Update 2 </div>
    </div>
    <div class="col-md-4 divbtnbg" id="b3">
      <div class="col-12">Update 3 </div>
    </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

Utilizing react.js and passing props as parameters in recursive functions

When using recursion, I encountered an issue where I am unable to pass the props parameter: class App extends React.Component { constructor(props) { super(props); this.state = { visible: this.props.root, a:this.props.a }; } toggle(){ thi ...

Utilizing HTML and CSS allows for creating a responsive layout with three elements such as this

Need help with CSS to align three elements in a row, where the first two are on the left and the third is on the right. The layout should adjust so that when the window size is smaller, the second element moves below the first while the third element stays ...

Binding multiple forms in backend ASP.NET MVC using Managed Extensibility Framework (MEF)

We are facing a challenge where we need to send multiple forms in one Ajax (jQuery) Call to an ASP application. The jQuery code we are using is as follows: var formContainer = { Form1 : form1.serialize(), Form2 : form2.serialize() } ...

When a nested CSS Grid is inserted into an HTML table element, it causes horizontal overflow

     Generating an invoice dynamically with a CSS grid poses some challenges. To maintain a specific format, I need to define the number of rows and columns in advance along with column widths. Using template rows and columns for this purpose restrict ...

NPM: Handling multiple prehooks with the same name

Is it possible to have multiple prehooks with the same name in my package.json file? For example, having two instances of pretest: "scripts": { "start": "react-scripts start", ... "pretest": "eslin ...

Knockout JS: Choosing specific dropdown elements

My array doorsForSite contains a list of doors, each with its own set of schedules. Here is how it looks: var scheduleList = new[] { new { ScheduleId = "Schedule1",ScheduleName = "Always On" }, new ...

React, Axios, and the PokeAPI are like a team of explorers navigating an

Trying to enhance my React abilities, I decided to follow this tutorial on creating a list of names using PokeAPI. However, I hit a roadblock at 11.35 into the tutorial while implementing the provided code snippets in both App.js and PokemonList.js: fu ...

Modify the parent's style in CSS based on the presence of certain specified children

I'm working with an HTML element that can contain a child with the ID 'slideshow' <div id='content'> <div id='slideshow'> </div> </div> Alternatively, it could have a different child like t ...

Arrangement of tables using HTML and CSS on the outdoor patio

Looking for advice on how to align buttons in the last column of a table outside of the table but in the same row. The attached image shows the current layout: https://i.sstatic.net/Ex5AR.png ...

There seems to be a problem with the JavaScript function as the indexOf property is undefined

function filteredArray(arr, elem) { let newArr = []; Iterating through each element of the multidimensional array. for (let i=0;i<arr.length;i++){ for (let j=0;j<arr[i].length;j++){ If the value matches the argument passed, assi ...

Displaying Unicode CSS Font Awesome Icons as Boxes in a React Project

I have incorporated the jPlayer example into a create-react-app. Encountering an issue where font-awesome icons are displaying as boxes in this CodeSandbox illustration. https://codesandbox.io/s/peaceful-heisenberg-d59nz?fontsize=14&hidenavigation=1&a ...

IE presenting problems with JQuery content loaded via Ajax

I operate a website that showcases various products, each with a corresponding link to a fancybox displaying detailed information about the product (detailed.php file). <a class="fancy fancy'.$_GET['type'].'" href="detail.php?id=&ap ...

The `$(this).data()` function removes any excess data from a database, stopping at the first occurrence of a

One issue I am encountering is when retrieving data with a whitespace. I need the complete string of data, not the trimmed version. When retrieving "data-title" or "data-type", the data gets cut at the whitespace. I tested by setting a static string in ...

Display Image based on AngularJS value

Within my data, there exists a value {{catadata2.EndorsementList['0'].Rating}}. This value can be either 3, 4, or 5. Based on this value, I am looking to display the image <img src="/assets/img/rating.png" /> a certain number of times. For ...

What is the equivalent of Buffer.from(<string>, 'hex') in Python?

I am currently facing the challenge of translating a Typescript library into Python. The specific library I am working with is bs58 in Typescript and its counterpart base58 in Python. My issue arises when attempting to replicate the following code: const ...

How can I generate an Xpath for the given element?

I am trying to find the Xpath for the specific name (I1888 - Child 1.1) without using the contains function. Currently, I am using the following xpath: "//span[contains(@class,'TreeTitleRed')][contains(.,'Child 1.1')]", but I would like ...

The function is not being executed when using $scope.$apply()

I am in need of a customized click directive that can execute the passed code using scope.$apply(). $(elem).on('click', function(){ scope.$apply(attrs.wdClick); }); Everything works smoothly when I pass something like wd-click="something = ...

What could be causing the error when attempting to retrieve an index using the window variable?

I'm facing a strange issue where I am trying to utilize a variable that I define as follows: window.params['variable'] = { ... }; Within the function that I am using, the code looks like this: function q() { ... // for example return n ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

Using Zen coding to insert an image source from a selection of options

I am attempting to use zen coding to generate a series of img tags with the src attribute populated by a list of filenames. Below is the list of filenames I have, followed by the desired output: filenameA.jpg someotherone.jpg anotherimage.jpg sample.jpg ...