Is there a way to incorporate a transition effect into the show more category button, so that hidden li items are smoothly revealed?

Essentially, I attempted to display only 10 items by default and hide the rest, which become visible when clicking on the "more category" div at the bottom. This was achieved using jQuery, and now I am looking to add some transition effects to the toggle window that opens up quickly. Any suggestions?

var max = 10;
jQuery('#menu-categories').each(function () {
    if (jQuery(this).find('li').length > max) {
        jQuery(this).find('li:gt(' + max + ')').hide().end().append('<li class="sub_accordian"><div class="show_more">More Categories</div></li>');

        jQuery(this).find('.sub_accordian').click(function (e) {
            jQuery(this).siblings(':gt(' + max + ')').toggle();
            if (jQuery(this).find('.show_more').length) {
                jQuery(this).html('<div class="show_less">Close Menu</div>');
            } else {
                jQuery(this).html('<div class="show_more">More Categories</div>');
            };
        });
    };
});

Check out how the show more div looks like.

Answer №1

Introducing a method utilizing the css transition. Upon page load, jQuery swiftly calculates the open and close height of the UL. These values are stored in attributes for easy access.

var max = 3;
jQuery('#menu-categories').each(function() {
  let oh = 0;
  jQuery(this).find('li').each(function() {
    oh += +jQuery(this).height()
  })
  oh += jQuery(this).find('li').height()
  jQuery('#menu-categories').attr('open-height', oh);

  if (jQuery(this).find('li').length > max) {
    jQuery(this).find('li:gt(' + max + ')').hide().end().append('<li class="sub_accordian"><div class="show_more">More Categories</div></li>');
    jQuery(this).attr('close-height', jQuery(this).height())
    jQuery(this).css({
      height: jQuery(this).height(),
      visibility: 'visible'
    })

    jQuery(this).find('.sub_accordian').click(function(e) {

      jQuery(this).siblings(':gt(' + max + ')').toggle();
      if (jQuery(this).find('.show_more').length) {
        jQuery('#menu-categories').css('height', jQuery('#menu-categories').attr('open-height'))
        jQuery(this).html('<div class="show_less">Close Menu</div>').hide().fadeIn();
      } else {
        jQuery('#menu-categories').css('height', jQuery('#menu-categories').attr('close-height'))
        jQuery(this).html('<div class="show_more">More Categories</div>').hide().fadeIn();
      };
    });
  };
});
#menu-categories {
  visibility: hidden;
  background: #f0f0f0;
  transition: height .5s;
  overflow: hidden;
  height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id='menu-categories'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>

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

What is the best way to set unique heights for various ion-grid components?

Situation: I am facing an issue with my Ionic/Angular app. The screen layout, as shown in the image provided and on Stackblitz, includes two ion-grids with different background colors - green and red. Goal: My goal is to assign a percentage height to each ...

Acquire the HTML content with a simple click

Is there a method to emphasize the current HTML element when a user hovers their mouse over it (not just one object, but anything on the page) and then copy the content of that particular element when clicked? Are there any JavaScript techniques or librar ...

Display a pop-up video player when a button is clicked to watch multiple videos on a webpage utilizing jQuery/Javascript

I am in need of assistance with integrating multiple embedded YouTube videos (using iframes) that appear on the screen after a user clicks a custom button. While there are solutions available for single videos, I am struggling to make it work for multiple ...

Tips for expanding a React class using typescript

Let's consider a basic example: interface BaseProps { name: string; } class BaseClass<P extends BaseProps> extends React.Component<P, void> { } interface SuperProps { } class SuperClass extends BaseClass<SuperProps> { } M ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

Ways to maximize the value of an inline class

I have this unique inline class that needs modification <DIV title="AST Infrastructure" class="ms-acal-item ms-acal-color4" style="BORDER-LEFT-WIDTH: 0px; HEIGHT: 17px; BORDER-RIGHT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 1px; POSITION: absolute; LEFT: 22px; ...

Implementing Voting Functionality with Ajax Submission

Can anyone help me with getting ajax functionality to work properly for my Acts_As_Votable buttons? Here's the current code I have: post_controller.rb def favorite @post = Post.find(params[:id]) @post.upvote_from current_user respond_to do |f ...

What is the best way to sift through an array containing arrays of arrays that hold objects?

My attempt to filter an array of arrays of objects is not working as expected. constructNewGrid(filterText){ if(searchText == ""){ this.constructedGrid = this.fullGrid; return; } this.constructedGrid = []; this.c ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

Angular tree dropdown menu structure

Check out this functional jsfiddle: working example for the secondary level In the jsfiddle, I am able to assign a brand from the first dropdown and a model from the second dropdown to each car created through ng-repeat. It is all working smoothly. Howev ...

Comparing data in Knockout js

I'm trying to compare the values of the variable name by id, but I'm not sure how to do it. Here is what I have so far: if (this.name == self.copy().indexOf(this.id).name) { alert('equals'); } else { alert('not equals&apo ...

Is it possible for you to fix this HTML and PHP code for my Contact Form?

I am struggling with the Contact Form coding on my Dreamweaver CS6 website. Could someone please review my code and help me identify the issue? I believe the HTML is correct, but there seems to be an error in the PHP portion. HTML: <form action="ass ...

Interactive modal window showcasing details of the first item upon clicking any item button

I am in the process of creating a dress shopping website. The home page showcases all dresses along with their descriptions in a grid layout, each accompanied by an 'Add to Cart' button. However, upon clicking the button, a modal popup appears sh ...

Combine various form input values with a specific name into a single array using Node.js with the npm forms package

Despite my efforts, I am struggling with a seemingly simple task. Even after scouring through Stack Overflow and various documentation, nothing seems to work, prompting me to seek help here. My goal is to handle an HTML form (templated through JADE) and s ...

Issues with Dreamweaver CS5's live preview feature and compatibility with different web browsers

Hey there, I recently sliced an image using Fireworks and exported it to HTML. After opening the HTML file in Dreamweaver, I saved it as PHP and everything seemed fine. Then, I replaced some images with HTML input tags and buttons, setting their width and ...

Why is AngularJS $http response undefined?

My $http call in AngularJS is returning undefined when I try to access the data in my controller. What could be causing this issue? Despite using .then to handle promises, the data passed to the controller seems to become undefined. Can you help me figure ...

Is it possible to incorporate a fadein animation into a function?

Developing the entire HTML structure using JavaScript is one of my skills. Here is a snippet as an example: function generateHeader () { $('body').append( $('<header>') .attr('id', "main-header") ...

What is the optimal tech solution for creating a cross-browser introduction video that is compatible with both iPhone and IE6?

We are in need of an introductory video for our website that must be compatible with all browsers, including Safari on the iPhone and IE6. Our plan is to use a combination of flash with HTML5 fallback or vice versa. Has anyone tried this before? We want t ...

Guide on how to assign a value to a textbox according to the selected option from a dropdown menu

I need a feature where, depending on the selection made in a dropdown menu, data should be automatically filled into the next input field. For instance, if the options in the dropdown menu are NETWORK1, NETWORK2, NETWORK3, selecting NETWORK1 should popula ...

JavaScript Spinlocks Explained

What is the best way to implement a spinlock in JavaScript? I am attempting to load multiple images and I need to wait until all of them have finished loading before proceeding. My current approach involves using a spinlock like this: for(...) image[i ...