Ways to reset a JQuery/JavaScript filter

I am currently working on a list of div items that are being filtered and sorted using JavaScript. Each item animates as it enters the screen, scaling up to its final size.

However, when I apply filters using buttons, items that are already displayed do not replay this entrance animation.

My goal is to reset the filter every time a new button is selected so that every item always animates into place, regardless of what is being filtered or whether it is already on the screen.

Check out my CodePen for a live demonstration

<div class="filter-list">
  <button class="active btn" id="all">All</button>
  <button class="btn" id="oranges">Oranges</button>
  <button class="btn" id="apples">Apples</button>
  <button class="btn" id="bananas">Bananas</button>
</div>
<div class="grid">
  <div class="artist-img item oranges">oranges</div>
  <div class="artist-img item apples">apples</div>
  <div class="artist-img item bananas">oranges</div>
</div>

Here's the JavaScript code:

 var $items = $(".item");
  var $btns = $(".btn").click(function () {
    if (this.id == "all") {
      $items.show();
    } else {
      var $el = $("." + this.id).show();
      $items.not($el).hide();
    }
    $btns.removeClass("active");
    $(this).addClass("active");
  });

And the CSS styles used for the entrance animation:

@keyframes entrance {
    0% {
      transform: scale(0.5);
    }
    100% {
      transform: scale(1);
    }
  }
  .grid > div {
    padding: 1rem;
    position: relative;
    animation-duration: 0.5s;
    animation-name: entrance;
  }

Answer №1

To reset the elements and bring them back to their initial state of 0% on the animation, you should first hide all elements before showing the desired ones. Avoid directly hiding and showing as it may not allow enough time for the animations to complete. Use a timeout of 1 ms to ensure that each element has time to return to 0%. Here's an updated version of the code:

var $items = $(".item");
var $btns = $(".btn").click(function() {
  $items.hide();
  setTimeout(() => {
    if (this.id == "all") {
      $items.show();
    } else {
      $("." + this.id).show();
    }
  }, 1);
  $btns.removeClass("active");
  $(this).addClass("active");
});
button {
  padding: 1rem;
}

.filter-list {
  margin: 1rem;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 1rem;
  row-gap: 1rem;
}

.grid>div {
  background: #000;
  padding: 3rem;
  animation-duration: 0.5s;
  animation-name: entrance;
  color: #fff;
}

@keyframes entrance {
  0% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filter-list">
  <button class="active btn" id="all">All</button>
  <button class="btn" id="oranges">Oranges</button>
  <button class="btn" id="apples">Apples</button>
  <button class="btn" id="bananas">Bananas</button>
</div>
<div class="grid">
  <div class="artist-img item oranges">
    Oranges
  </div>
  <div class="artist-img item apples">
    Apples
  </div>
  <div class="artist-img item oranges">
    Oranges
  </div>
  <div class="artist-img item oranges">
    Oranges
  </div>
  <div class="artist-img item apples">
    Apples
  </div>
  <div class="artist-img item bananas">
    Bananas
  </div>
  <div class="artist-img item apples">
    Apples
  </div>
  <div class="artist-img item bananas">
    Bananas
  </div>
</div>

Answer №2

Is this JavaScript function accomplishing your goal?

 var $elements = $(".element");
  var $buttons = $(".button").click(function () {
    if (this.id == "all") {
      $elements.show();
    } else {
      $elements.hide();
      var $selectedElement = $("." + this.id).show();
      // $elements.not($selectedElement).hide();
    }
    $buttons.removeClass("active");
    $(this).addClass("active");
  });

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

Guide on adding dual horizontal scroll bars to a v-data-table (Vue / vuetify)

Currently, I am working on Vue / Vuetify and experimenting with the v-data-table component. While creating a table, I noticed that it has a horizontal scroll bar at the bottom. https://i.stack.imgur.com/noOzN.png My goal now is to implement two horizontal ...

The beautiful synergy between Vuetify's v-input component and overflow animation

I am having trouble implementing an overflow animation on vuetify's v-text-field component. Despite my efforts, I can't seem to make it work as intended: <script setup> const text = 'very long long long long long text' </scri ...

React modal not triggered on click event

As a newcomer to react, I am exploring a modal component import React, { useState, useEffect } from 'react'; import { Modal, Button } from "react-bootstrap"; function TaskModal(props) { return ( <Modal show={pro ...

"Unlocking the potential of JSON: A guide to retrieving and displaying three specific fields in

My PHP service is returning the following data: [[1,"16846"],[2,"16858"],[3,"16923"],[4,"16891"]] Within my HTML, I have ajax set up to fetch this information; $.ajax({ type: 'POST', url: 'getDadosGrafico.php', ...

Using jQuery's .html() method will remove the selected attribute from the dropdown menu option

When generating HTML dynamically, a select element is included. After choosing an option inside it, everything works fine. For example: <div id="test"> <select> <option value="1">1</option> <option value="2" selec ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

Turn off all the styles associated with a specific CSS selector

Looking for a solution to override CSS rules for the .lp-caption selector? .lp-caption { -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-right-colors: none; -moz-border-top-colors: none; backgr ...

Unable to locate a resolution for the error message "Warning: Task "uglify" not found"

Below is the content of my Gruntfile.js: module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ uglify: { start: { files: { 'js/script.min.js': ['js/script.js&a ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

When the menu active item is clicked, the header will automatically scroll to the top

I've implemented a sticky header using CSS and JavaScript along with a mega menu. However, I've encountered an issue where when scrolling to the bottom and clicking on the "more" link in the dropdown, the page scrolls back to the top. This is the ...

Retrieving JSON information using JavaScript

I am encountering an issue with the "Ion.RangeSlider" library. I am attempting to dynamically load values via JSON, but I am unable to get the slider to accept the data from the "from" field. It is important that the value is not hardcoded since the user h ...

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

Transforming vanilla JavaScript into jQuery

Is there a more efficient way to write this code using jQuery? It's functioning properly in Firefox but not in Safari or Chrome without any error messages, making it difficult for me to troubleshoot. Any suggestions or insights would be greatly appre ...

Accessing a variable from one function within another function in Vue

How can I access and utilize the ctx variable from the initGrid() function in the drawGrid() function? Despite trying to use "this," it seems that the variable cannot be accessed within the drawGrid() function. <script> export default { data: ( ...

ID is not receiving the CSS styles

I'm having trouble applying my CSS to a specific img ID element on the page. I've been trying to solve this for about 30 minutes with no luck. The strange thing is, I have two other elements with the same HTML and CSS that are working correctly. ...

Leverage JavaScript variables within JSON objects

I have a JavaScript variable that I want to use in a JSON format. var add = mixItems[i][0] + "," + mixItems[i][1]; jQuery.getJSON("wp-content/plugins/proteinmixer/php/addtocart.php" , function(data){ }); Here is the PHP code: require_once('../../.. ...

Uploading images dynamically using Ajax and PHP upon submission

Currently, I am working on a modal that submits information and an image through a form to a database using PHP and JavaScript. However, my expertise in JavaScript is limited, so I could use some assistance. So far, I have successfully inserted data from ...

Failed to input data into MySQL database's dynamic field

I have encountered an issue while trying to enter dynamic fields into a MySQL database, and I am struggling to figure out the cause of the problem. Below are both the HTML and PHP files provided; I would greatly appreciate any assistance in identifying and ...

.NET and Azure integration for asynchronous HTTP requests

My Ajax function is running smoothly on my local machine when the site is accessed locally. However, an issue arises when deploying it to Azure - if one of the parameters contains a line break, I get an error message: "The specified URL cannot be found", i ...

Steps for extracting URL parameters from AWS API Gateway and passing them to a lambda function

After successfully setting up my API gateway and connecting it to my lambda function, I specified the URL as {id} with the intention of passing this parameter into the lambda. Despite numerous attempts using both the default template and a custom one for ...