What is the best way to design a dynamic menu using HTML, CSS, and jQuery, where each li element gradually disappears?

Consider this menu structure:

<ul class="main-menu">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

My task is to dynamically hide the items on resize, starting with item 6, followed by item 5. The resulting menu should look like this:

<ul class="main-menu">
  <li>1
    <ul>
        <li>6</li>
        <li>5</li>
    </ul>
  </li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

Answer №1

If you want to enhance efficiency, there are definitely ways to do so. The current code serves as an illustration of the solution.

Here is your HTML:

<ul class="main-menu">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

And here is the JS code:

$( window ).resize(function() {
    var liWidth = 100;
    if($(window).height()/$('.main-menu').children().length < liWidth){
        console.log('here');
        if($('.main-menu li').first().find('ul').length > 0){
            $('.main-menu li').first().find('ul').append('<li>'+$('.main-menu li').last().html()+'</li>');
            $('.main-menu li').last().remove();
        }
        else{
            $('.main-menu li').first().append('<ul><li>'+$('.main-menu li').last().html()+'</li></ul>');
            $('.main-menu li').last().remove();
        }
    }

    else if($(window).height()/($('.main-menu').children().length + 1) > liWidth){
        console.log('there');
        if($('.main-menu li').first().find('ul li').length === 1 ){
            $('.main-menu').append('<li>' +$('.main-menu li').first().find('ul li').html() + '</li>')
            $('.main-menu li').first().find('ul').remove();
        }
        else if ($('.main-menu li').first().find('ul li').length > 1) {
            $('.main-menu').append('<li>' +$('.main-menu li').first().find('ul li').last().html() + '</li>')
            $('.main-menu li').first().find('ul li').last().remove();
        }
    } 
});

The end result can be viewed on this Fiddle link.

Answer №2

After comprehending your explanation, this is how I plan to tackle the task at hand. My approach involves constructing an HTML structure containing the submenu and concealing it using CSS. Furthermore, I will employ the resize() function to dynamically show or hide the element based on specific conditions.

Answer №3

Indeed, all you need is CSS and media queries to achieve the desired outcome.

HTML

  <ul class="main-menu">
    <li>1
      <ul id="nav2">
       <li>6</li>
       <li>5</li>
     </ul>
    </li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li id="five" >5</li>
    <li id="six" >6</li>
 </ul>

CSS

#nav2 li {
   display:none;
}

@media only screen and (min-width : 150px) and (max-width : 580px)
 {
#nav2 li {
    display:block;
}
#five,#six {
    display:none;
}

}

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

Breaking down JavaScript arrays into smaller parts can be referred to

Our dataset consists of around 40,000 entries that failed to synchronize with an external system. The external system requires the data to be in the form of subarrays sorted by ID and created date ascending, taken from the main array itself. Each ID can ha ...

Getting the Request Body Content in Express Middleware

Currently, I am in the process of developing a small API logger to use as an Express middleware. This logger is designed to gather data from both the request and response objects, then store this information in a JSON file on disk for later reference. Her ...

Is there a way to modify the value of a constructor key once it has already been defined?

I am currently working on a simple constructor exercise where I need to update a value after the constructor has been created. Even after changing the value to true, the cat is still not making its noise. Challenge parameters The constructor function wi ...

Tips for creating a responsive image with a gradient overlay

Having trouble articulating my query, so here's a fiddle: https://jsfiddle.net/8zsqydj0/ .background-img-wrapper:before { content: ""; top: 0; left: 0; position: absolute; height: 100%; width: 100%; background: linear-gradient(to righ ...

Adjust the value before moving to the next tab, or if you choose to leave the

Looking for help to display a popup message when a user edits any value? Check out this resource that I found. It currently only triggers when moving to another page, but I need it to work within an Ajax tab system as well. Here is the code I have tried: ...

What could be causing AngularJS to fail to send a POST request to my Express server?

I am currently running a Node Express server on localhost that serves a page with AngularJS code. Upon pressing a button on the page, an AngularJS controller is triggered to post a JSON back to the server. However, I am facing an issue where the post requ ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Creating markers for every value in a table using Google Maps API v3

Looking for some guidance here. I have a table with multiple values that I need to process using a function. Could someone help me with a suitable loop in jQuery or JavaScript that can achieve this? I'm still learning the ropes of these languages. My ...

Ways to include margin right for a table

Here is the HTML code I am working with: <table width="100%;> <tr><hr style="width:100%;"></hr></tr> <tr> <span style="float:left">abc</span> <span class="noindex" ...

Maintain a consistent size for the material UI drawer, preventing it from resizing when the content size fluctuates

Incorporating Material UI into my project, I decided to use a drawer for navigation. However, within the drawer, there are Collapsible lists that expand when clicked. The issue arises when the list text items are lengthy, causing the drawer to unexpectedly ...

Is it possible to obtain the outcome from the MySQL database in JSON format?

Currently, I am utilizing Node.js along with MySQL for my project. My goal is to retrieve data from the MySQL database in JSON format. Can anyone provide me with some guidance on how to achieve this? ...

Is it necessary to publish a package for client-side usage on npm?

I'm struggling to understand the recent trend of using npm to publish client-side packages that have no dependencies. Take for example a simple class that extends HTMLElement and can only be used in the browser by adding a script tag to an HTML file. ...

Can date ranges be utilized as separate date items on the time scale in D3.js?

I have a chart that resembles the one shown below, however, there is a crucial component missing. Currently, my time scale follows the standard format as depicted in the first picture. I am looking to convert it to the time scale seen in the second picture ...

Creating a CSS section that expands with a minimum height of 100% and perfectly centers its content vertically

Seeking an elegant solution for having sections with a minimum height of 100% (window height). The div should expand to fit the content if it exceeds 100%, and vertically center the content within the div if it is smaller. I have managed to find a simple ...

Issue with React Native Hook where converting a function into a class variable results in 'undefined'

We are currently in the process of converting a react native function into a class so that we can implement state management compatible with Firebase's real-time database. It recently came to our attention that Hooks cannot be used within a class, so ...

Why won't XML load with jquery GET, but does load with a direct link and PHP?

When it comes to pulling in an xml feed, I've been experimenting with using php and simpleXML to load it. Interestingly, I can access the direct link without any issues. However, when attempting to utilize jquery and GET method, the request times out ...

Reasons for the failure of file uploads from the React frontend to the backend system

Recently, I embarked on a new project that involves using React for the front-end and Node for the back-end. The main requirement of this project is to upload multiple images from the front-end, with the back-end handling the file uploads to Cloudinary. I ...

How can one retrieve elements from a loaded webpage?

I've been using the jQuery function .load() to load a page and I'm trying to find a way to access HTML elements within the loaded page from the source page once it's finished loading. The only method I've come across so far is to add pa ...

What causes the variation in the appearance of the navigation bar across different pages?

I'm struggling to understand why the Navigation bar has extra padding or margin on top only on certain pages, while it looks fine on the Homepage. I've dedicated countless hours to this issue and I am feeling completely frustrated. If you' ...

Vanishing Tooltip following an implementation of the backdrop-filter

I'm having an issue with the blur effect on my background image. Although it works well, my tooltips also end up being blurred behind the divs: https://i.stack.imgur.com/BMdh4.png Is there a way to ensure that my tooltips stay on top of the subseque ...