Interactive Filtered Image Gallery Powered by JQuery

Greetings!

I am seeking assistance in refining the concept for a JQuery gallery that incorporates two filters. Currently, my approach involves utilizing the filters as class names and ids. When a user clicks on a filterable 'button' with an id, it triggers an action to be performed on all associated classes. While I can successfully filter each element individually, I face an issue when trying to select multiple filters simultaneously. My goal is to display only those cards that belong to both selected filters, excluding any others. Presently, even if a card belongs to just one filter, it still shows up.

Regarding the challenge of selecting multiple elements concurrently, I find myself at a loss. I am struggling to figure out how to streamline or "reduce" this code. Any innovative ideas on simplifying the code would be greatly appreciated as I continue to learn JQuery.

My current project involves designing and constructing a webpage featuring a JQuery gallery comprised of div containers, which I refer to as "cards." Each card contains a title, description, and more. Users can navigate through these cards by filtering based on category (competency) and day of the week, aiding them in selecting the most suitable option.

At present, I manually write out individual cases for each filter, which may not be the most efficient method but it gets the job done! However, I aspire to refine the functionality so that selecting filters from both categories results in showing only cards that meet both criteria. As mentioned earlier, currently, even if a card falls under just one filter, it remains visible.

In addition, I am constructing the page using Bootstrap.

HTML Setting Up 2 Filters

<!-- First Filter, by Category -->
    <div class="col-md-2 col-sm-2 col-xs-2">
      <img id="buttonAll" src="..."/>
    </div>
    <div class="col-md-2 col-sm-2 col-xs-2">
      <img id="button1" src="..."/>
    </div>
    <div class="col-md-2 col-sm-2 col-xs-2">
      <img id="button2" src="..."/>
    </div>
    <div class="col-md-2 col-sm-2 col-xs-2">
      <img id="button3" src="..."/>
    </div>
    <div class="col-md-2 col-sm-2 col-xs-2">
      <img id="button4" src="..."/>
    </div>

<!-- Second Filter, by Day -->    
      <p id="dayAll">Any Day</p>
      <p id="monday">Monday</p>
      <p id="tuesday">Monday</p>
      <p id="wednesday">Wednesday</p>
      <p id="thursday">Thursday</p>
      <p id="friday">Friday</p>

HTML A Card / Gallery Setup

<div class="container">
  <div class="row">
    <!-- START CLASS CARD -->
            <div class="class-card sort-button1 sort-button2 sort-button3 sort-button4 monday">
                <h1>Class Title</h1>
                <h3>Monday @ 3:00 PM</h3>
                <p>Develops:
                    <img class="tiny-button" src="https://sephora.csod.com/clientimg/sephora/welcome/20180106_Careerfest_Button_Tiny_1.jpg"/>
                    <img class="tiny-button" src="https://sephora.csod.com/clientimg/sephora/welcome/20180106_Careerfest_Button_Tiny_2.jpg"/>
                    <img class="tiny-button" src="https://sephora.csod.com/clientimg/sephora/welcome/20180106_Careerfest_Button_Tiny_3.jpg"/>
                    <img class="tiny-button" src="https://sephora.csod.com/clientimg/sephora/welcome/20180106_Care...

   <!-- START CLASS CARD -->
            <div class="class-card sort-button2 monday">
                <h1>Class Title</h1>
                <h3>Monday @ 12:00 PM</h3>
                <p>Develops:
                    <img class="tiny-button" src="https://sephora.csod.com/clientimg/sephora/welcome/20180106_Careerfest_Button_Tiny_2.jpg"/>
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam tristique placerat erat, ut varius quam pulvinar eget. Ut mollis quam at maximus vulputate. Suspendisse posuere turpis eu accumsan tempor....               

JS Implementing Filter 1:

// Filter 1: by Day

// Show cards for all days of the week by default
$('.monday').show();
$('.tuesday').show();
$('.wednesday').show();
$('.thursday').show();
$('.friday').show();

// Actions upon clicking different day filters
$('#dayAll').click(function() {
    $('.monday').fadeIn();
    $('.tuesday').fadeIn();
    $('.wednesday').fadeIn();
    $('.thursday').fadeIn();
    $('.friday').fadeIn();
});

$('#monday').click(function() {
    // showing Monday cards while hiding others
    $('.tuesday, .wednesday, .thursday, .friday').fadeOut();
    $('.monday').fadeIn();
});

// For Tuesday filter
$('#tuesday').click(function() {
    // show Tuesday specific cards and hide others
    $('.monday, .wednesday, .thursday, .friday').fadeOut();
    $('.tuesday').fadeIn();
});

// Implementing similar logic for remaining days...
...

JS Implementing Filter 2:

// Filter 2: by Category (Competency) 

// Showing cards for all competency categories by default
$('.sort-button1').show();
$('.sort-button2').show();
$('.sort-button3').show();
$('.sort-button4').show();

// Handling actions after triggering different category filters
$('#buttonAll').click(function() {
    $('.sort-button1').fadeIn();
    $('.sort-button2').fadeIn();
    $('.sort-button3').fadeIn();
    $('.sort-button4').fadeIn();
});
// Additional filter actions for button1, button2, etc.
...

Feel free to explore the full project on CodePen.

As a beginner in JQuery programming, I acknowledge that the JS part could use some optimization. The iterative steps without loops or variables might appear rudimentary, but they serve their purpose for now. If you have suggestions on enhancing this aspect, I am all ears. Thank you for your input!!

Answer №1

Hello there, I've implemented several modifications to your logic.

To begin with, examining your options is crucial. Each of your category options contains a class="categoryFilter". This attribute aids in selecting them all effortlessly. Additionally, they are equipped with a data-target representing the class on which the option should be sorted. While all categories possess this, it remains empty for the 'all' category.

When looking at your day options, you'll notice that they also have a class="dayFilter" and a data-target specifying the class upon which they should be filtered.

The workflow involves first obtaining references to all cards and storing them in a variable. A similar process is applied to all day and category filters as well.

Initially, we display all cards just like before.

Subsequently, bindings are created for the category and day filters. Upon clicking any filter, the clicked filter receives the selected class while the same class is removed from all other related filters. Afterward, the filterCards method is called, which both filter event handlers utilize.

The core functionality of this method includes resetting any previous filtering by showing all cards initially. Following this, we identify the selected dayFilter and categoryFilter. The data-target associated with these selections - signifying the class to be filtered on – is then added to an array prefixed with a dot (.) indicating it as a class selector.

Post-array check, if elements exist within, all elements not matching our filters are identified using the combined selectors. By hiding these non-matching elements, we achieve our intended combined filtering.

The opacity-changing logic demonstrated in your codepen has been omitted here. Nonetheless, this implementation showcases one method for executing a combined filter effectively.

Answer №2

Are you satisfied with this?

// Sorting Buttons

var filters = [];

$(".competency-menu img").on('click', function(){
    $(".competency-menu img").addClass('PASSIVE').removeClass('ACTIVE');
    $(this).removeClass('PASSIVE').addClass('ACTIVE');
    filters[0] = $(this).data('filter');
    applyFilter(filters);
});

$(".day-menu > p").on('click', function(){
    $(".day-menu > p").addClass('PASSIVE').removeClass('ACTIVE');
    $(this).removeClass('PASSIVE').addClass('ACTIVE');
    filters[1] = $(this).data('filter');
    applyFilter(filters);
});

function applyFilter(filter){
  $(".class-card").fadeOut();
  if(filter[0] && filter[1]){
    $("." + filter[0] + "." + filter[1]).fadeIn();
  } else if (filter[0]){
    $("." + filter[0]).fadeIn();
  } else if (filter[1]){
    $("." + filter[1]).fadeIn();
  } else {
    $(".class-card").fadeIn();
  }
}
.ACTIVE {
opacity: 1.0;
}
.PASSIVE {
opacity:.45;
}
.class-card {
    padding: 30px;
    border: 1px #d6d6d6 solid;
    border-radius: 5px;
    width: 30%;
    margin: 15px;
    float: left;
}
.class-card h1 {
    font-family: "Times New Roman", Times, serif;
    font-weight:bold;
}
.class-card p {
    font-size:14px;
    line-height:18.27px;
    margin-top:10px;
}
.class-card ul li {
   margin:9px 0px 0px 15px;
   color:#6f7179;
}
.space-6 {
height:32px;
display:block;
}
.day-menu p {
    display: inline-block;
    padding: 10px;
    text-transform: uppercase;
    font-size: 14px;
    color: #c1c1c1;
    letter-spacing: 1;
}
<!-- THIRD PARTY PLUGINS --> 
    <!-- BOOTSRAP CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- TOUR CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tour/0.11.0/css/bootstrap-tour.css">
    <!-- SLIDER CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightslider/1.1.6/css/lightslider.css">
    <!-- LIGHTBOX CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css">


<!-- IN-HOUSE PLUGINS -->
    <!-- DAILY DOSE THUMBNAIL: MAIN CSS -->
    <link rel="stylesheet" href="https://sephora.box.com/shared/static/26p04xz6frwy51fbt3d0kby8d55eisde.css">
    <!-- DAILY DOSE THUMBNAIL: MOBILE BREAKPOINTS CSS -->
    <link rel="stylesheet" href="https://sephora.box.com/shared/static/7x469uo9iofg276dm79yduzj1vujjj08.css">
    <!-- CSOD Overrides -->
    <link rel="stylesheet" href="https://sephora.box.com/shared/static/8zp03gs0o59gz43i4gr33i4nhwp6h719.css">
    <!-- LightSlider Overrides -->
    <link rel="stylesheet" href="https://sephora.box.com/shared/static/aminxarvz1xsrkp21p470kz3tyanwcpe.css">
  <!-- Core CSS Styles -->
    <link rel="stylesheet" href="https://sephora.box.com/shared/static/uwonou0jrd00r7q8or538r8a92jwpusp.css">


<span class="space-6"></span>
    



<div class="container">
        <div class="row">
        <img width="100%" src="https://sephora.csod.com/clientimg/sephora/welcome/20180106_Careerfest_Oldies_But_Goodies.jpg"/> 
        </div><!-- end row -->
    </div><!-- end container -->

<span class="space-6"></span>


<div class="container">
        <div class="row">
        <img width="100%" src="https://sephora.csod.com/clientimg/sephora/welcome/20180106_Browse_Courses_by_Competency_V2.jpg"/> 
        </div><!-- end row -->
    </div><!-- end container -->
    
    
    
<span class="space-6"></span>


<div class="container">
    <div class="row">
        <div class="col-md-offset-2 col-md-8">
            .... (content continues) ...

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 transmit and retrieve JSON data

I am using jQuery and attempting to send a JSON object to an ASPX file that contains a web method, but I keep receiving an HTTP 500 error. How can I adjust my code? I suspect there may be errors in the C# file, but I'm not sure how to correct them. An ...

Modify the standard placement of choices in MUI

Currently, my UI is powered by MUI. I have various options displayed in the image below: https://i.sstatic.net/YKoyV.png Everything looks good so far. However, I wish to reposition the options container further down. (It is currently set at top: 64px ...

The requested URL cannot be loaded due to the Access-Control-Allow-Methods in the preflight response not allowing the PUT method

When making an Ajax request using AngularJS, I encountered a problem with the $http method. It works well with both get and post requests, but throws an error with put. Response Header : Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type ...

Tips for utilizing comment tags efficiently

I have encountered an issue with IE7 where my CSS is not functioning properly. In an attempt to target IE7 and lower versions specifically, I inserted IE comment tags into the HTML code. However, despite my efforts, it does not seem to be effective. Initia ...

Is your Javascript failing to update window.location.search?

Looking to update the URL search parameters when a user enters them in the search panel on a page. Currently attempting: $( document ).ready(function() { if ($('.o_website_license_search_panel').length) { $('.o_website_license_s ...

The variable __dirname has not been defined

Can anyone explain why my Google Cloud Run instance is unable to recognize the __dirname variable? My expressjs server contains the following code: import path from 'path'; const App = express() .get('/*', (_req, res) => { ...

Issue on my website specifically occurring on Google Chrome and mobile devices

Hello, I seem to be having a CSS issue. Interestingly, my menu (burger menu) works perfectly fine on Firefox but is not functioning properly on Chrome and mobile devices. When I click the button, the menu doesn't open. Has anyone encountered a simil ...

Is there no minimum length requirement for jQuery Regex check?

Here is the code snippet I am working with: <input type="text" id="Desc" placeholder="Beschreibung (Optional)'" pattern="^[a-zA-Z\wäöüÄÖÜß\- ][a-zA-Z0-9\wäöüÄÖÜß\- ][\w-.,@&amp;(){}\[\]:;!?&bso ...

Processing of hierarchical JSON structure

I have a JSON array that I am trying to duplicate only once while keeping it unique. Here is the code I have attempted: return_data = {}; return_data.planner = [{ "date": "2019-08-30T12:10:08.000Z", "event": [{ "name": "Event 1", "col ...

Difficulty in accurately identifying the current page on the appbar

I'm attempting to make the active page in my navbar stand out by giving it a white background color and skyblue text. However, for some reason, I can't get the text color to display as skyblue in the appbar. You can see how it currently looks in ...

Troubleshooting: Issues with jQuery Dropdown Menu

I'm currently working on a website that includes a settings feature with a button. My goal is to have the options and other links display in a dropdown menu when hovered over. Although I have written what I believe to be the correct code, it's no ...

Feetable information in JSON format

I have a footable that I want to populate with JSON data. I am familiar with how to fill the array, but I am using some PHP to retrieve my data using the echo json_encode method. When I console.log the response, it gives me : [{"idsecteur":"1","nomsecte ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

Ensuring divs are centered when resizing the page

Is there a way to center an unordered list of tables while ensuring that it remains centered even when the window is resized? The list should move each table to a new line if they can no longer fit. Check out the code snippet below for reference: <d ...

The issue with the datatable row button functionality is not functioning as expected within the

I am facing an issue with my Jade Template code where I am trying to trigger a JavaScript function when a button is clicked on each row. Despite following the documentation for DataTables and Jade, I am unable to figure out what mistake I am making. It see ...

Excessive calls to the component update in React with Javascript are leading to application crashes

componentDidUpdate() { // Retrieving trades from the database and syncing with MobX store axios.get(`http://localhost:8091/trade`) .then(res => { this.props.store.arr = res.data; }) } After implementing this code, my ...

Solid colored fill for the active item in the Bootstrap navbar

As I work on constructing a web page using Bootstrap 5 with a fixed top navbar, I am aiming to have the "active" item highlighted with a solid background color similar to the example shown here. Upon inspecting the page using developer tools, I noticed th ...

The font size and div box size remain consistent when utilizing the append function

I am attempting to create a container with full width and a height of 150px, but it's not displaying correctly, and the background color is not showing up as expected. Additionally, when I use the jQuery append function to add text, the font size rema ...

Is it possible to utilize promises to execute a function once the initial one has completed its task?

I am struggling to wrap my head around promises. Currently, I am working on a project where I scrape a website using node and NPM, then save the data to a CSV file. While I can successfully retrieve the data with multiple scrapes, I want to ensure that th ...

Attempting to show the name in AngularJS

I've been working on mastering Angular JS, but I'm facing a challenge with displaying the user I just added to the database on the next page. While I can display other users, the newly added user's data just won't show up! I've tri ...