What is the best way to ensure that only one div is toggled at a time while using the toggle class function?

$(document).ready(function(){
  $("#items").children().click(function(){
    $(this).toggleClass('clicked');
  });
});
.clicked {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='items'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

In the current setup, clicking on a div makes it turn red. However, you can click on multiple divs to turn them all red. How can I modify the code so that only one div is highlighted in red at any given time?

Answer №1

Give this a shot!

$(document).ready(function(){
    $("#items").children().click(function(){
        $(this).toggleClass('clicked') // toggling the class of the current element
               .siblings('div') // selecting siblings of the current element
               .removeClass('clicked'); // removing the 'clicked' class from the siblings

    });
});

$(document).ready(function() {
  $("#items").children().click(function() {
     $(this).toggleClass('clicked').siblings('div').removeClass('clicked');
  });
});
.clicked {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='items'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

Answer №2

Eliminate the clicked class from all other related div elements.

Utilize siblings() to choose the neighboring elements.

Gather the adjacent siblings of each element in the selected elements, potentially with a filter.

$(document).ready(function() {
  $("#items").children().click(function() {
    $(this).toggleClass('clicked').siblings('div').removeClass('clicked');
  });
});
.clicked {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='items'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

Answer №3

$(document).ready(function() {
  $("#items").children().click(function() {
    $(this) //clicked element
        .add('.clicked', this.parentNode)//add already '.clicked' child element in jq set
        .toggleClass('clicked');//toggle class for all elements in set
  });
});
.clicked {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='items'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

Answer №4

To exclude the current selection, you can utilize removeClass along with not:

$(document).ready(function(){
  $("#items").children().click(function(){
    $('#items > div').not($(this).toggleClass('clicked')).removeClass('clicked');
  });
});
.clicked {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='items'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

An alternative concise method:

$(document).ready(function(){
  $("#items").children().click(function(){
    $('.clicked').not($(this).toggleClass('clicked')).removeClass('clicked');
  });
});

Answer №5

Here's a way to achieve this:

$(document).ready(function(){
  $("#items").children().click(function(){
    $(this).siblings().removeClass('selected');
    $(this).addClass('selected');
  });
});

Answer №6

Hey there, let's try it this way!

$(document).ready(function(){
      $("#items > div").click(function(){
       $("#items").children().removeClass('clicked');
        $(this).addClass('clicked');
      });
    });

$(document).ready(function(){
  $("#items > div").click(function(){
   $("#items").children().removeClass('clicked');
    $(this).addClass('clicked');
  });
});
.clicked {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='items'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</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

Tips for transferring data from one tab to another tab using Greasemonkey

Is it possible to extract data from a webpage in one tab and then input it into a textarea on a different page opened in a separate browser tab using Javascript and Greasemonkey? ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

React: maintaining referential equality across renders by creating closures with useCallback

I want to make sure the event handling function I create in a custom hook in React remains referentially equal across renders. Is it possible to achieve this using useCallback without specifying any variables it closes over in the dependencies list? Will o ...

Tips for displaying XML content within an AngularJS application using HTML

I have a string containing data: var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel> </rss>" ; My goal is to display this string on a web page in the proper XML format. <channel& ...

Tips for retaining the original text value even after clicking the submit button

import java.util.Map; import java.util.HashMap; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org ...

How can I uniquely identify and edit individual cells within an ng-grid using the bgColor property?

I need some clarification regarding Angularjs ng-grid. Is there a way to distinguish between the edit-cell and non-edit-cell in ng-grid? Perhaps using different background colors? ...

Is there a way to retrieve user input without having to submit the form?

I am looking to capture user input without the need for submission, and then pass it through an AJAX method as a parameter to an action. Despite trying various methods, I have not been able to find a solution. Below is the code snippet: <input type="t ...

Storing the Token from the AJAX Login API Call in JavaScript: Best Practices for Keeping Credentials Secure

After sending my credentials to a login API, I received a successful response containing user data and a token. I would like to know how I can store this information so that the user doesn't have to log in every time. Is it possible for me to save the ...

Unable to Trigger onClick Event with react-bootstrap Navbar Dropdown in Combination with react-router-dom

In my React application with react-bootstrap, I have a Navbar component that displays a dropdown menu for different brands. However, I noticed that the second brand option (Tommy Hilfiger) is always the one active by default, as if it is automatically cl ...

Controlling Material-UI using a custom .css stylesheet

Are there alternative methods for customizing Material-UI components using CSS stylesheets? I'm aware of the {makeStyles} method and JSS overrides, but I find it messy in the code and confusing when trying to modularize it in other files. Is there a ...

When using the RxJs Pipe with MAP in Angular and Ionic, it may not return a value in windows, but it works perfectly in Mac when used with HttpClient

I'm currently using RxJs Pipe with Map for a network request in my Angular/Ionic project. Interestingly, while I do receive a successful response in the network log, the MAP function fails to return any value. Notable Observations Strangely, this fu ...

An issue arose upon restarting my Eclipse software

Upon restarting my Eclipse, I encountered the following error message: "Plug-in com.android.ide.eclipse.adt was unable to load class com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor." As a beginner, could you advise me on how to addres ...

React is having trouble resolving the path required

Having an issue with the tracking-js library in my project. I'm using React and despite checking my package.json and confirming that the module is installed, I keep receiving errors indicating that the module cannot be found. This is how I am attempti ...

Several queries for directions on Google Maps are resulting in the same response being returned for all requests

I've been experimenting with the Google Maps Directions service to retrieve three different travel methods for the same route (driving, walking, and bicycling). Despite successfully iterating through the array of methods and setting them in the respec ...

Discovering numbers within a JSON object and extracting them - a step-by-step guide

If I have a JSON object coming from a random dataset and want to search through it to manipulate the number values, how can I achieve this? Looping through the object using for...of allows me to get the keys, but I'm unsure how to access every key-val ...

Trying to organize JSON data by multiple parameters using jQuery

Regarding the topic discussed in this thread; I have successfully managed to sort an Array of JSON Objects by two fields. Additionally, the discussion mentions: "To include additional columns for sorting, simply add them to the array comparison." // ...

Leveraging JQuery to retrieve the string value from an onclick() event

Curious if there's a more efficient approach to tackle this issue, decided to seek input from the SO community... There's a third-party web page over which I have no control in terms of how it's displayed, but they do allow me to integrate ...

Baconjs exclusively retrieves the final debounce value

Below is a code snippet that showcases my current implementation: let watcher; const streamWatcher = bacon.fromBinder(sink => { watcher = chokidar.watch(root, { ignored: /(^|[\/\\])\../ }); watcher.on('all&a ...

Obtain the current URL in a Node.js configuration file

In my application using the express framework, I have the following code in my app.js file: var express = require('express'); var app = module.exports = express(); var config = require('./config.js')(app, express); // Including ...

Issue with displaying multiple checkboxes using Materialize CSS in combination with Leaflet for web-mapping overlays

I'm currently using Materialize 0.97.7 along with Leaflet 1.0.1 (the latest version). <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet-src.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com ...