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

Get tabular information in xlsx format by utilizing the xlsx npm package for download

I have been attempting to convert my json-like data into an xlsx file format. I utilized the xlsx npm package and followed various code samples available online, however, when trying to open the file in Excel, I encountered the following error: https://i.s ...

Executing a node (console) command from a JavaScript file using AJAX on click

Hey, I'm a beginner in node.js and I have a question: Imagine I have a web application with a button. When the user clicks this button, I want to execute a node console command (e.g. node socket.io). Here's my attempt using jQuery: $( ".button ...

Is there a way to remove <font> tags using Javascript designMode?

Currently, I am in the process of developing a WYSIWYG editor as a hobby project. My approach involves utilizing an iframe with design mode enabled and leveraging the execcommand feature in JavaScript to implement the editor functionalities. For instance, ...

What's causing the show/hide feature to malfunction within the for loop in Vue.js?

I've encountered an issue with my for loop where the show/hide functionality doesn't seem to work despite everything else functioning properly. I've been trying to troubleshoot this problem without success. <div id="app"> <ul> ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

When using Inertia.js with Laravel, a blank page is displayed on mobile devices

Recently, I've been working on a project using Laravel with React and Inertia.js. While everything runs smoothly on my computer and even when served on my network (192.168.x.x), I encountered an issue when trying to access the app on my mobile phone. ...

I am facing an issue with my React/Redux API where it is not logging out correctly and displaying [[

As a beginner in the coding world, I've run into some challenges while working with a React/Redux API. Following along with Bucky Roberts' YouTube tutorial, I decided to replace his static names object with an API that I then integrate into my r ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

What is preventing hover from working correctly?

I'm having trouble getting images to display when hovering over text. Can anyone offer suggestions on what might be causing this issue? The images are being downloaded when clicked, so I know they're in the correct path. I've checked for com ...

Utilizing CSS to print specific columns on a separate page at regular intervals

I am facing a challenge with printing a very large HTML table, which is dynamic in the sense that the number of rows and columns can vary. When printing, the rows that exceed the page length are automatically continued on the next page. However, I also nee ...

Transform URL in AngularJS Service

An issue I'm facing with the app I'm developing is that users need to be able to change the IP address of the server where the REST API is hosted. The challenge lies in the fact that while the address is stored in a variable that can be changed, ...

Unusual happenings detected in Magellan Fixed with Foundation 5

I need help creating a product summary sidebar similar to Apple's. I'm using Magellan but it seems to break the page when the width is below 960 pixels. It might be related to the table, but I'm not sure. Any suggestions or assistance would ...

JavaScript button for displaying and hiding all content in one click

I came across a tutorial on W3Schools that showed how to create collapsibles, and I thought it would be great to have buttons that could expand or collapse all at once. I've been trying to implement this feature using the code provided in the tutorial ...

Edgeshelper failing to update mesh positions

I want to create a custom colored box with different colored edges. To accomplish this, I'm using the following code to generate the box and its edges. I've encapsulated both elements within an object3D since there will be multiple objects in the ...

Can you tell me what this code on Facebook is for?

Upon inspection of Facebook's activity in my browser, I stumbled upon the following code snippet: for (;;);{"t":"refresh"} Attempting to decipher its purpose reveals an infinite loop. Can you identify its function? ...

When HTML elements are dynamically inserted through JavaScript using quilljs, they may cause conflicts with the layout properties

I am currently working on creating a simple webpage layout similar to that of Stack Overflow, with a sidebar and a main content area that can scroll. In my case, the content area is intended to host a QuillJS text editor. To integrate the QuillJS editor i ...

Having issues with Bootstrap 4's bg-inverse not displaying correctly?

While attempting to replicate the navbar example from Bootstrap's documentation, I encountered an issue where the background color of the navbar was not loading properly. <nav class="navbar navbar-inverse bg-inverse"> <a class="navbar-br ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...

Oops! There seems to be an issue with an invalid character in the literal true value while making a POST request to the API with JSON data. The expected character should be

Can anyone help me solve an issue I am facing while trying to use the POST method to insert data using JSON in JS code? When I attempt the transformation, I receive an error message stating: "ERROR: invalid character ' ' in literal true (e ...