Guide on how to show or hide divs using keyword filters

My webpage features various cards with different keywords:

<div class="item">
    <div class="hashtags">
        <span><a href="#">Technology</a></span>
        <span><a href="#">Innovation</a></span>
    </div>
</div>
<div class="item">
    <div class="hashtags">
        <span><a href="#">Healthcare</a></span>
        <span><a href="#">Cybersecurity</a></span>
    </div>
</div>

In addition, I have pills that can be toggled on/off:

<div class="hashtags">
    <span class="active"><a href="#">Healthcare</a></span>
    <span class="inactive"><a href="#">Technology</a></span>
    <span class="inactive"><a href="#">Innovation</a></span>
    <span class="inactive"><a href="#">Cybersecurity</a></span>
</div>

The goal is to click on a pill for "Healthcare", which then displays only the items containing "Healthcare" in their hashtag class, hiding all other items. I've been looking into how to filter/toggle content based on specific criteria, but haven't found a solution yet. Here's the JavaScript I have so far, which handles toggling the active/inactive classes of the pill styling:

    $('.hashtags>span').click(function() {
    $(this).toggleClass('inactive');
    $(this).toggleClass('active');
    });

I'm aware there are ways to search HTML and compare strings using JS or jQuery, but I'm unsure if that's the best approach. Any input or advice would be greatly appreciated. Thank you!

Answer №1

Below is a comprehensive example with additional comments included within the code.

$('.hashtags > span').on('click', function(e) {
  e.preventDefault();
  // capturing the selected value
  var storedValue = $(this).text();
  // passing it to a function for processing
  highlightHashtag(storedValue);
});


var highlightHashtag = function(value) {
  // looping through each element
  $('.hashtags > span').each(function() {
    if($(this).text() !== value) {
      // setting non-matching elements as inactive
      $(this).removeClass('active');
      $(this).addClass('inactive');
    } else {
      $(this).removeClass('inactive');
      $(this).addClass('active');
    }
  });
  
};
.active {
  background-color:green;
}

.inactive {
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="item">
    <div class="hashtags">
        <span><a href="#">Healthcare</a></span>
        <span><a href="#">Mobility</a></span>
    </div>
</div>
<div class="item">
    <div class="hashtags">
        <span><a href="#">Finance</a></span>
        <span><a href="#">Mobility</a></span>
    </div>
</div>

Answer №2

Personally, I believe it enhances the structure of your HTML if you incorporate some custom tags. Have a look at this quick example:

Custom attributes like data-something can prove to be quite beneficial within your HTML code.

CSS serves to highlight which classes are associated with specific objects.

Feel free to experiment with the code below or check it out on JSFiddle here:

$('.hashtags>span').click(function() {
                $(this).toggleClass('inactive');
                $(this).toggleClass('active');
                var tag = $(this).attr("data-tag");
                var related = [];
                $('.hashtags').each(function(index){
                    $(this).children( "span" ).removeClass("active");
                    $(this).children( "span" ).addClass("inactive");
                    if($(this).attr("data-tag") !== undefined && $(this).attr("data-tag").indexOf(tag)>-1) {related.push(this);}
                });
                $(related).each(function(){
                    $(this).children( "span" ).removeClass("inactive");
                    $(this).children( "span" ).addClass("active");
                });
            });
.inactive > a{
                color: red;
            }
            .active > a{
                color: blue;
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
    <div class="hashtags" data-tag="healthcare finance">
        <span><a href="#">Healthcare</a></span>
        <span><a href="#">Mobility</a></span>
    </div>
</div>
<div class="item">
    <div class="hashtags"  data-tag="finance mobility">
        <span><a href="#">Finance</a></span>
        <span><a href="#">Mobility</a></span>
    </div>
</div>

<div class="hashtags">
    <span class="active"  data-tag="finance"><a href="#">Finance</a></span>
    <span class="inactive"  data-tag="healthcare"><a href="#">Healthcare</a></span>
    <span class="inactive"  data-tag="managedServices"><a href="#">Managed Services</a></span>
    <span class="inactive"  data-tag="mobility"><a href="#">Mobility</a></span>
</div>

Answer №3

After carefully reviewing your query, here is the recommended course of action: start by concealing all the elements marked with .items, then reveal only those items bearing a hashtag that matches your selected text.

ULTIMATE RESOLUTION

$('.hashtags>span').unbind('click').click(function() {
    var text = $(this)
            .toggleClass('inactive')
            .toggleClass('active');
    var items = $('.item').hide();
    $('.hashtags>span.active').each(function(){
        var t = $(this).find('a:first').text() ;
        items.each(function(){
            var i = $(this);
            //identify and display items containing a link with the active hashtag
            if(i.find('.hashtags>span>a:contains(\'' + t + '\')').length > 0) {
                i.show();
            }
        });
    });
});

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

Text in anchor vertically centered across browsers

Take a look at my JsFiddle project here: http://jsfiddle.net/JxXHE/ I want to ensure that the text in the menu items is perfectly centered vertically, with an 8px margin from the top and bottom in all browsers that are supported. The list of supported bro ...

Adjusting an item according to a specified pathway

I am currently working on dynamically modifying an object based on a given path, but I am encountering some difficulties in the process. I have managed to create a method that retrieves values at a specified path, and now I need to update values at that pa ...

Transforming timestamps to month day, year format and back again without the use of any NPM packages

I have developed a microservice that converts Unix timestamps to a format like Dec 01, 2017 and vice versa. The microservice is deployed at this link: timestamp I am wondering if there is a better way to achieve this without using third-party NPM modules. ...

Creating an Image Slideshow on Your Website

I'm looking to create an image slideshow on my website that functions similarly to the one found at . However, I want the images to occupy the entire screen rather than having smaller images like the reference site. Can anyone offer guidance on how t ...

Get information from one div and implement it in a different div

I am working on an application that creates div boxes dynamically and loads images through AJAX to place inside these boxes. To avoid unnecessary loading, I want to check if a box already exists before loading images. If it does exist, then I would like t ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

Tips for showcasing images within buttons in HTML

Currently, I am working on setting up a local web server to manage various functions in my car using a RPi 4. For this project, I am incorporating libraries such as nodejs, npm, express, ejs, and rpi-gpio. My goal is to utilize rpi-gpio to operate relays ...

How to retrieve the current event handler's value with jQuery

To assign an onclick event handler using jQuery, I simply use the following code: $('#id').click(function(){ console.log('click!'); }); Now, my question is how can I retrieve a reference to the function that is currently handling th ...

Leveraging Enjoyhint within nextJS

I am attempting to create a code tour using EnjoyHint, but encountered an error after installing the xbs-enjoyhint library. The error reads: Server Error - ReferenceError: CanvasRenderingContext2D is not defined. This issue is within the jquery.enjoyhint ...

Using JavaScript to display a line using `document.write`

I'm having trouble displaying a line using the Document.Write function in JavaScript. When I submit the form, the line briefly appears and then disappears Any ideas on why this might be happening? <!DOCTYPE html> <html> <head& ...

What is the process for importing a file with an .mts extension in a CJS-first project?

Here's a snippet from a fetchin.mts file: import type { RequestInfo, RequestInit, Response } from "node-fetch"; const importDynamic = new Function("modulePath", "return import(modulePath);") export async function fetch(u ...

What is the preferred choice: using camelCase in CSS with Styled Components or Emotion for standard React development?

When I'm coding with React Native, I use the styled properties that follow most of CSS syntax and are formatted in camel case. For instance: //... <Component style={styles.container} /> //... const styles = StyleSheet.Create({ ...

Ways to sort data based on dropdown selection in MVC Razor

I am facing a requirement where I have a list of vendors that are displayed on the page load. Additionally, there is a dropdown menu which acts as a filter for these vendor records when its value changes. This is my view: <div class="half-left"> ...

Directive in Angular for customer management with filtering and sorting functionality

I am struggling to organize the JSON object by userType using ng-repeat. While I have successfully retrieved and displayed the data, my ISSUE is that I need to sort and display two different tables for the following list: One for MARRIED individuals and an ...

What are some ways to implement querySelectorAll in conjunction with htmx?

I'm currently using htmx, an amazing library with a small issue that I'm struggling to resolve. htmx utilizes querySelector to find elements for swapping or updating, for example with hx-swap="...", hx-target="...". How can I use querySelectorAll ...

I am interested in implementing unique custom designs for the labels on highchart plotlines

I am trying to customize the style of a highchart plotline label. I have been using the borderRadiusRight option but it does not seem to be taking effect. Below is the code I am working with. Please review. Highcharts.chart('chart', { //... ...

Utilizing Bootstrap exclusively within a designated container div

Incorporating bootstrap into my TYPO3 frontend plugin has been beneficial, but I am looking to apply it selectively within a specific div. This way, the class without_bootstrap remains unaffected by any changes made by the bootstrap classes. Consider this ...

Sortable jQuery div designed to resemble a chessboard

I am currently using the sortable() function in jQuery to create a grid-like "chessboard" within a div. My goal is to allow users to drag and drop sortable items into predetermined spaces, similar to a chess board. In addition to the basic sortable example ...

Python and JavaScript fundamental interaction

My current setup involves having a local HTML page named leaflet.html, which is being shown in an embedded browser within a python-tkinter application. Within the leaflet.html file, there exists a straightforward JavaScript code snippet that includes a fu ...

Pause the loading of information for a brief 2-second interval using jQuery's ajax feature

I want to enhance the user experience by loading search results using jQuery ajax within a div container. To achieve this, I am looking to introduce a 2-second delay before displaying the results or show them only after the user has entered at least three ...