jQuery remove highlighting only if it is currently applied

I am in need of a simple solution to remove the selected class when clicking on an already highlighted button. I want only one button to be highlighted at a time.

http://jsfiddle.net/7wy7sjm5/1/

The reason why I first remove the class for all buttons is because I only want the clicked button to be highlighted, not the previously clicked ones. Additionally, if a button that is already highlighted is clicked again, I want to remove the highlight. I hope this explanation is clear.

$(".details-btn").on("click", function(){
var $this = $(this);
//Add/Remove selected for button
$(".details-btn").removeClass("selected");
$this.toggleClass("selected");});

I have tried different approaches, such as using .each() to cycle through each instance of the button and remove the class if it has it, but none of them are working as I would like.

Answer №1

If you want to achieve this, you can utilize the .not() method.

To clarify, eliminate the .selected class from all elements with the class .details-btn except for the current one using not(this). Then, implement the toggle() function.

$(".details-btn").on("click", function() {
  var $this = $(this);
  $(".details-btn").not(this).removeClass("selected");
  $this.toggleClass("selected");
});

$(".details-btn").on("click", function() {
  var $this = $(this);
  $(".details-btn").not(this).removeClass("selected");
  $this.toggleClass("selected");
});
* {
  margin: 0;
  padding: 0;
  font-size: 1.1em;
}
table {
  border: 1px solid;
  text-align: center;
}
thead {
  background-color: #ddd;
}
th {
  border-bottom: 1px solid;
}
td {
  width: 140px;
}
.details-btn {
  background-color: #dad1ea;
  width: 50px;
  margin: 4px auto;
  border: 1px solid #4b3575;
  border-radius: 5px;
  cursor: pointer;
}
.selected {
  color: #fff;
  background-color: #4b3575;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th scope="col">Data</th>
      <th scope="col">View</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>
        <p class="details-btn">+</p>
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td>
        <p class="details-btn">+</p>
      </td>
    </tr>
    <tr>
      <td>3</td>
      <td>
        <p class="details-btn">+</p>
      </td>
    </tr>
    <tr>
      <td>4</td>
      <td>
        <p class="details-btn">+</p>
      </td>
    </tr>
    <tr>
      <td>5</td>
      <td>
        <p class="details-btn">+</p>
      </td>
    </tr>
    <tr>
      <td>6</td>
      <td>
        <p class="details-btn">+</p>
      </td>
    </tr>
  </tbody>
</table>

Answer №2

Prior to removing, store the state of the class and then reapply it if it was originally present. Check out this updated Fiddle.

// Save the initial class state.
var hadClass = $(this).hasClass("selected");
// Remove the class from all elements.
$(".details-btn").removeClass("selected");
// If the class was not present before removal, add it back. Otherwise, do nothing.
if (!hadClass) {
    $(this).addClass("selected");
}

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

ReactJS: Error - Unable to execute this.props.data.map as a function

I am currently using reactjs and facing an issue when trying to display JSON data, either from a file or server: Uncaught TypeError: this.props.data.map is not a function In my quest for a solution, I have explored: React code throwing “TypeError: thi ...

Utilize jQuery to populate checkbox and label attributes with elements from an array

I am looking to populate attributes for 4 checkboxes and their labels from specific arrays without appending the entire markup. I have everything set up in the markup and just need to fill in the attributes based on the selection from a select menu. var ...

Exploring ways to navigate through JSON data within an HTML document by utilizing jQuery to create a tree view structure

I am facing a challenge in iterating JSON data in a tree view structure. While I can iterate the json value for the first level, I am encountering difficulty in iterating the data nested inside parent arrays for the second and third levels. One issue coul ...

I developed a real estate listing web application using AngularJS, where I chose to use the $http service to fetch data. Unfortunately, the data retrieval process seems to be failing. Can someone help me identify the issue?

Hey there, I have identified three files which seem to be at the root of the problem. Instead of using POST, GET, PUT, DELETE methods, I am intentionally experimenting with $http. Let's take a look at mansionsController.js file: angular .module( ...

What is the frequency of occurrences for a variable within a table?

I am currently working on finding a way to create a query that can determine how many consecutive times a particular value repeats before changing. Specifically, I am interested in counting the number of instances the "yes" column repeats before encounteri ...

"Customize Your CSS Dropdown Menu with Dynamic Background Color for div Elements

I recently put together a website dedicated to watches. Feel free to check it out at horology dot info. (Please refrain from sharing the direct URL of my site in your reply.) I'm curious as to why the dropdown menu, sourced from , is showing up unde ...

Removing an item from a JSON list

Is there a way to remove a specific element (e.g. by using its id) from a JSON array? A delete button can be used to achieve this task, passing the id as a parameter. For instance, how would one go about deleting an item with an id of 2 : Note: The id n ...

Is your Angular5 service failing to transmit data?

I have two components in my code, A and B. Component A contains a form with data that I want to send to component B. However, it seems like component B is not receiving any data. Here is the code for Component A: import { MyService } from 'path/my ...

Angular: Leveraging real-time data updates to populate an Angular Material Table by subscribing to a dynamic data variable in a service

Seeking guidance on how to set up a subscription to a dynamic variable (searchData - representing search results) for use as a data source in an Angular Material Table. I have a table-datasource.ts file where I want to subscribe to the search results from ...

Enable vertical scrolling on the second row of a table while keeping the first row fixed as the table header (CSS)

While embedding the Ace Editor in a Chrome popup window, I encountered a challenge. My goal was to keep the first row of text always visible at the top while allowing the rest of the Editor to fill the screen. However, there is an issue with a vertical scr ...

Using `texture.needsUpdate = true` in Three.js can cause significant performance issues due to its slow execution

I am currently working on a project involving a Three.js scene where I need to update textures after a certain period of time. However, I have noticed that updating the textures is causing a significant slowdown in the FPS, dropping it to 1-2 FPS for sever ...

Encountering a discord bot malfunction while on my Ubuntu server

My discord bot runs smoothly on my Windows 10 setup, but when deployed to the server running Ubuntu Server 20, it encounters a specific error. The issue arises when trying to handle incoming chat messages from the server. While I can read and respond to m ...

What are the steps to activate code suggestion with codemirror?

My goal is to implement CodeMirror for enabling users to input code in various languages like CSS, HTML, and JavaScript. One specific requirement is to provide hints to the user when typing code in CSS mode. div { padding- } The system should prompt th ...

Why is the jQuery Ajax AutoComplete feature not functioning properly?

Hey there, I'm currently utilizing CodeIgniter along with Ajax AutoComplete for jQuery in my project. When setting up my autocomplete feature in jQuery, I used the following code: a = $('.city').autocomplete({ serviceUrl: "<? echo $ ...

Implement a sub-routine in Office.js Javascript Word add-in that utilizes asynchronous execution context

Lately, I've been exploring the world of developing an Office.js add-in for Word and have found some success. One task that seems to come up frequently in my add-in is searching and replacing text, which needs to be performed by various action buttons ...

Issue with displaying V-For elements in Bootstrap Dropdown Button

Take a look at my Vue.js (3) component, styled with Bootstrap (5): <template> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle btn-link text-decoration-none text-dark" type="button" ...

The requested function is nowhere to be found within the confines of my Controller module

While working on a personal project, I encountered an issue where a function from another class in a separate Java file is not being found, even though it is defined in the respective class. EventView.js: displayEvent(event){ this.EventTitle = event. ...

Display a Bootstrap input button group addon, where the first button has rounded corners only after the second button has been hidden

I am working on a button group and need to hide the second button dynamically. However, I am facing an issue where the first button has a 90° border. How can I adjust the code below to display button 1 with a rounded border? If I decide to hide "button ...

Using the useState Hook: What is the best way to add a new item to the end of an array stored in the state

I'm currently working on a project using Next.js and Tailwind, where I am trying to populate an array using the useState Hook. My intention is to iterate through the array using the map function and add items to the end of the array until there are n ...

Inserting text into a textarea and watching it disappear

<textarea class="skinCondition-field vlongtext clear ui-input-text ui-body-d ui-corner-all ui-shadow-inset" type="text" placeholder="Share details of your current skin condition (e.g. normal, dry, flaky, etc). Optionally, mention any past skin issues, m ...