Selecting multiple categories using jQuery

HTML:

<ul id="selector">
    <li><a href="#" class="group1" rel="group1">group 1</a></li>
    <li><a href="#" class="group2" rel="group2">group 2</a></li>
    <li><a href="#" class="group3" rel="group3">group 3</a></li>    
</ul>
<ul id="elements">
    <li class="group1">1</li>
    <li class="group1 group2">1 and 2</li>
    <li class="group3">3</li>
    <li class="group1 group3">1 and 3</li>
    <li class="group2 group3">2 and 3</li>
    <li class="group2">2</li>
</ul>

JQuery:

$('#selector a').click(function(event){
    event.preventDefault();
    var $this = $(this),
        target = $this.attr('rel');
    $('#selector a').removeClass('active');
    $this.addClass('active');
    $('#elements li').addClass('inactive');
    $('#elements li.'+target).removeClass('inactive').addClass('active');
});

CSS:

#selector {margin: 10px 0; background: #eee; list-style: none; padding: 0px;}
#selector li {display: inline-block;}
#selector li a {display: block; margin: 0 4px; padding: 5px; background: #aaa;}
#selector li a.active {color: #fff;}

#elements {margin: 0px; padding: 0px; list-style: none; background: #eee;}
#elements li {display: inline-block; width: 100px; margin: 4px; text-align: center; background: #ccc; padding: 40px 0;}
#elements li.inactive {opacity: 0.2}

This code showcases an interface where users can click group selector elements to highlight all elements belonging to that group. The goal is to allow multiple group selectors to be active at the same time, highlighting elements that belong to all selected groups simultaneously. If someone clicks on group1 selector, elements with that class are highlighted. Then if someone clicks on group2, only elements belonging to both groups are highlighted. If one of the group selectors is unclicked, only elements with the remaining group class are highlighted. When no group is selected, all elements have full opacity.

Any suggestions on how to modify the existing code to achieve this behavior?

Visit this link for an example of the current functionality.

Answer №1

One approach to achieving this is by enclosing all the elements in a container and applying the specified class to it, which can then be used to format the relevant items. Instead of manipulating classes extensively, we can opt for toggling the clicked class.

View jsFiddle Example

JavaScript

$('#selector a').click(function(event){
    event.preventDefault();
    var group = this.className;
    $('#container').toggleClass(group);
});

CSS

#container #elements li {opacity: 0.2}
#container.group1 #elements .group1,
#container.group2 #elements .group2,
#container.group3 #elements .group3 {opacity:1;}

#container.group1 #selector .group1,
#container.group2 #selector .group2,
#container.group3 #selector .group3 {border:1px solid #000;}

Extension

If your aim is to activate '1 and 2' only when both 1 and 2 are active simultaneously, you can enhance the code as shown below to cover all scenarios. It may be more suitable to employ a JavaScript solution if dealing with numerous groups.

View Extended jsFiddle Example

#container.group1 #elements .group1:not(.group2):not(.group3),
#container.group2 #elements .group2:not(.group1):not(.group3),
#container.group3 #elements .group3:not(.group1):not(.group2),
#container.group1.group2:not(.group3) #elements .group1.group2:not(.group3),
#container.group2.group3:not(.group1) #elements .group2.group3:not(.group1),
#container.group3.group1:not(.group2) #elements .group3.group1:not(.group2),
#container.group1.group2.group3 #elements .group1,
#container.group1.group2.group3 #elements .group2,
#container.group1.group2.group3 #elements .group3,
#container:not(.group1):not(.group2):not(.group3) #elements li {opacity:1;}

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

Ways to grab attention as a visitor leaves a website

My company specializes in creating web surveys. Occasionally, we are asked if it is possible to conduct an exit survey on a website. This would involve displaying a "popup" to visitors as they are about to leave the site, prompting them to take a quick sur ...

How to boost the value of a property within a MongoDB document with Mongoose

Recently, I've been dealing with an array of objects named "items". This array includes different objects and I need to search for each object in MongoDB using the "baseId" found in the Base Document. Once I locate the matching object, I aim to update ...

React - the elusive nature of variable mutation

In my React app, there is a requirement to choose a specific version of a phone and then confirm the selection. Below is an excerpt from the React component's code: const App = () => { const [selectedVersion, setSelectedVersion] = useState(""); ...

Calculating the size of grid thumbnails or items using the calc() function

I am currently working on building a responsive portfolio grid that spans the full width of the screen. To achieve this, I have set the width of the items using calc() and ensured that the thumbnail image fills the entire div by applying the following CSS: ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

Using Four Different Colour Borders in CSS

Is it possible to create a CSS border with 4 different colors on one side? Currently, I have the following: #header { border-color:#88a9eb; } I aim to achieve a border featuring four solid colors split equally at 25% each. Can this be done? I am looking ...

I am attempting to utilize a code snippet that connects to an API and showcases the response without the need to refresh the page. Unfortunately, it does not appear to be functioning at the

Would anyone mind taking a look at this issue? I've added my API key, but the code I have isn't working as expected. It's designed to call the API and display the response without refreshing the page, but that functionality isn't curren ...

jquery survey quiz

Currently, I am attempting to develop a jQuery questionnaire, but my limited knowledge in the area is proving to be quite inadequate. So far, here is what I have: Upon clicking on "Questions," a pop-up window will appear with two questions. My goal is t ...

Displaying the most recent queries retrieved from a search API

Our web application built on angular.js utilizes a REST search API to query users within the system. The endpoint for searching users is: search/user?q='abc' Upon revisiting the web application, we aim to display the user's recent search ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

How can I ensure the end of the list is clearly visible?

I'm experiencing an issue where the last element in my list is getting cut off. When I check the console logs, I can see that it's rendering properly. If I remove the 'position: fixed' style, I can see the element at the bottom of the l ...

AngularJS Multi-select Dropdown Filter Logic

Thank you for taking the time to review my query. Currently, I am working on an AngularJS UI-Grid project where I have incorporated a Multi-select Drop-down Menu for the "First Name" column. However, I am facing challenges in implementing the logic similar ...

WebForm_OnSubmit redefined

My goal is to display Validation Messages in the Validation Summary and also show them in a separate popup. One approach I am considering is overriding the WebForm_OnSubmit method. function WebForm_OnSubmit() { if (typeof (ValidatorOnSubmit) == "fun ...

Could there be any issues with the structure of my mongoose schema?

I've been stuck for 3 hours trying to solve this problem. I can't seem to retrieve any data from my document. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = mongoose.Schema({ username: String ...

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

Leverage the potential of the value parameter within a mongoose scope

I am currently trying to retrieve emails of a user based on their id. However, I have encountered an issue due to the asynchronous nature of the mongoose function. Mail.find({receiver_id: '#id#'}, function(err, mails) { var result = []; ...

What is the best way to transfer data from a database query to Vue?

I am currently working on an API request that involves calling a SQL query within the function. I want to pass the results to a .vue page utilizing express-vue. Below is the code snippet for the API request: router.get('/search', (req, res, next ...

Is there a way to eliminate preflight requests from the $http header?

//loop through individual logins $rootScope.setting.instances.forEach(function(ins) { var header = { "Accept": "application/json", "Authorization": "Basic " + btoa( ins.uname + ':' ...

Expanding the width of the containing div using CSS

I have a main container with multiple smaller divs inside it. None of these small divs have specified widths. I want the black div to expand and fill up the entire space, stretching all the way to the ABC div on the right. This only needs to work in Chr ...