Rearrange elements within a div by clicking a button

I want to shuffle div elements with a click of a button using a dissolve animation in HTML5.

An example of what I am looking for is similar to this website

When you scroll on the page, there are links such as All, Intro, Solution. Clicking on any link should animate and rearrange all small divs.

I have attempted to create horizontal divs that hide on button click, but it doesn't function like this example:

View demo here

This is the code I used to shuffle divs on button click:

function shuffle(){
document.getElementById("b").style="display: none";
document.getElementById("a").style="opacity: 1; transform: translateX(0px) translateY(0px) translateZ(0px); transition: opacity 500ms ease 0s, transform 300ms ease 0s;";
}

The first div element hides, but there is no animation applied to the others as intended.

Answer №1

One issue is that using display: none does not provide a transition effect, causing the element to immediately disappear. To solve this, it's recommended to set a timeout after the transition properties have completed.

I've put together a simple CodePen example demonstrating a basic implementation of the "shuffle" effect.

Important Notes:

  • This solution may need further refinement for optimal performance.

  • It might be more effective in some cases to first apply the .filter() method to your data before applying the transition effect. This example focuses on achieving the desired visual effect rather than solely sorting functionality.

Check out the CodePen demo here

In this demonstration, I utilize flexbox for layout structure and incorporate transition with transform and width to create a minimize-to-center effect. Remember to adjust the transform-origin property to position the "close effect" correctly.

CSS Styles

.sorted-list {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  margin: 0;
  padding: 0;

  > li {
    background: #CCC;
    box-shadow: 0 2px 8px 1px rgba(33, 33, 33, 0.4);
    height: 150px;
    width: 25%;
    transform-origin: center center;
    transition: transform 0.45s ease, width 0.45s ease;

    &.hidden {
      transform: scale(0);
      width: 0;
    }

    &.d-none {
      display: none;
    }
  }
}

JavaScript Functions

const resetItem = (element) => {
  element.classList.remove('d-none');

  // Adding a slight delay to ensure smooth transition
  setTimeout((scopedElement) => {
    scopedElement.classList.remove('hidden');
  }, 1, element);
};

const hideItem = (element) => {
  element.classList.add('hidden');

  // introducing a delay for display: none since it lacks transition support
  setTimeout((scopedElement) => {
    scopedElement.classList.add('d-none');
  }, 300, element);
}

(function() {
  const nav = document.querySelector('nav');

  nav.addEventListener('click', (event) => {
    const { group } = event.target.dataset;

    // Resetting the list sort if no specific group is selected
    if (!group) {
      document.querySelectorAll('.sorted-list > li').forEach(resetItem);

      return;
    }

    // Ensuring visibility of elements within the specified group
    document.querySelectorAll(`.sorted-list > .group-${group}`).forEach(resetItem);

    // Hiding all other elements
    document.querySelectorAll(`.sorted-list > li:not(.group-${group})`).forEach(hideItem);
  });
})();

Answer №2

Currently, the website is fairly inactive. To improve user experience, make sure to implement the following:

Ensure that you have a well-organized data structure consisting of objects in order to effectively filter content, similar to this example:

[ { "type": "intro", "elmid": "something" } ]

  1. Create two classes - one for hiding and one for showing elements. Incorporate position animations with delays on all elements.
  2. Utilize Array.filter to filter content and dynamically add or remove classes as needed.
  3. Optimize performance by adding event listeners to parent elements rather than each individual element.

If you visit their page, you'll notice they are already implementing these practices.

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

I'm having trouble getting my application to output to the console. What could be the issue?

In my cr-route.js file, I have a function that ensures the user is authenticated before displaying their name. module.exports = function (app, passport) { // ===================================== // HOME PAGE (with login links) ======== // == ...

Tips for modifying button styles with CSS

I am facing an issue with a submit button on my form. The button currently has an image, which is unnecessary as the same image is used elsewhere on the page. I believe there might be a parent-child element problem preventing me from making the necessary c ...

Using a dynamic HTML interface, select from a vast array of over 50,000 values by leveraging the power

I am working on a project that includes a multiselect option with over 50,000 records. We are using AJAX to fetch data from the server based on user searches, which works fine. However, when a user tries to select all records by clicking the "check all" ...

Masking of the Navigation Button

I designed a responsive navigation bar, but in mobile view, the menu icon is being hidden by the menu headings when displayed. Check out the scenario below with a provided CodePen link. I attempted to adjust padding and float properties without success. An ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

How to access previous Redux state when navigating back using the Back button

Imagine a search page equipped with a search bar and various filters for the user to customize their data retrieval. As the user selects different filters, an API call is made to fetch updated data and the route path is also adjusted accordingly. However ...

Using AngularJS with the Chosen Plugin to pre-select a value in a dropdown menu

After following the guidance from this URL, I successfully incorporated the chosen plugin into Angular.js. Now that I can retrieve the value, my next objective is to have the selected value be pre-selected in the chosen dropdown menu. If anyone has a sim ...

Issue with Expo Google Places Autocomplete: ListView not clickable

I am currently encountering an issue with the GooglePlacesAutocomplete feature. When I input the address query, such as "São C," the 'listView' returns options like "São Caetano, São Paulo ...", however, when I attempt to select an option from ...

How to Use Absolute Positioning in Bootstrap 3.0 to Position Child Divs

I have a div block that needs to always be displayed at the bottom of the section, regardless of whether the section above is empty. The inner div should stay at the bottom of the section, as shown in the attached image. https://i.sstatic.net/cor6k.jpg T ...

Prevent modal from closing when tapping outside of it

I'm currently facing a challenge in creating a popup modal that cannot be closed by clicking outside the modal window. I have explored various solutions involving backdrops but none of them seem to be effective. Any assistance would be greatly appreci ...

Combine JQuery and backbone for enhanced functionality

I am currently using Backbone and Dyson to simulate an API. I'm attempting to display the results of the JSON but I encountered an error: Uncaught TypeError: self.template is not a function. ReservaCollectionView = Backbone.View.extend({ initialize: ...

Efficiently formatting text in a div container

How can I ensure that the text within a span is word-wrapped inside a div? https://i.sstatic.net/W691d.png Here is the code snippet: <div class="col-xs-6 choice btn btn-default" > <span class="pull-left">(Kepala) Bagian Purchasing (not lis ...

What is the best method for integrating opensea-js using a script tag in a vanilla HTML/JS environment?

Is there a way to incorporate opensea-js into an html/js project that does not rely on node.js? The source code for opensea-js is only available on github and npm at https://github.com/ProjectOpenSea/opensea-js I came across this link: However, when I tr ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...

Retrieve a JSON object from a Knockout observable array using the object's ID

I'm struggling to find examples of ko.observablearrays that deal with complex JSON objects instead of simple strings. I have an observable array containing a large JSON object with several properties, and I need to retrieve a specific object based on ...

What is the highest possible z-index value that can be applied in

Is there a specific limit to the CSS property z-index? Are there variations in accepted values among different browsers? How do browsers typically handle extreme z-index values? I recall reading about a potential maximum value for z-index somewhere, but I ...

Leveraging vuejs to dynamically insert a URL within a function

I am attempting to dynamically bind an image path inside a method. It seems feasible, but I'm uncertain if I am implementing the code correctly. Can someone review it? Essentially, I want to retrieve the selected image from the model rather than hardc ...

Using Laravel, I have managed to pass the start and end price range through an ajax get request, but I am facing difficulties in returning it correctly

Array Result after selecting price rangeWhen attempting to retrieve products based on the specified price range, I call the controller function with the input values: <script> function send(){ var start = $('#amount_start').val(); var ...

Emulate the selection process using element-ui and vue-test-utils

During my unit tests using Jest and Element-ui in Vue, I encountered an issue with a component containing a select element with 2 options. After selecting an option from the dropdown, I needed to verify that a specific action was called. 1) Everything wor ...

Tips for preserving values in ascx control on aspx page when a button is clicked

IDE: VS 2012 web In my test.aspx page, I am dynamically adding a user control using the code below: internal static List<ucTest> collTest = null; private void PageLoad() { // Called on page load and properly handled across postbacks. co ...