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

The Eclipse IDE is experiencing issues with the functionality of the JavaScript Number class

In my latest project, I decided to create a Dynamic Web Project using the Eclipse IDE 2019-12 along with Apache Tomcat 8.5.55 server. The main functionality of this project is that a user can input integers and receive their sum as an output. To ensure dat ...

What are the steps for submitting a form by clicking on text?

Whenever I try to submit a form by clicking on span id="ToolBarDownload", the form id="myformID" doesn't seem to get submitted. Can someone help me figure out what's wrong with my code? Any suggestions are greatly appreciated! Thanks! Also, just ...

The NodeJS environment is experiencing issues with async JavaScript functions returning undefined

I'm struggling to call a function that fetches data from an API, compares it with input, and should return either 0 or 1 for use in my code. However, the function is currently returning undefined. I can't seem to wrap my head around it. async fu ...

Determine the length of the content within an HTML container that has

I am attempting to retrieve the length of the container's content in HTML dynamically. However, I am only receiving the object instead of the desired result. <script> $(document).ready(function (e) { var adsense_box_len = $(&apo ...

What is the significance of using angular.forEach in this context?

While examining the functionality of the angular.forEach function: Below is the code snippet for angular.forEach: var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key) { this.push( ...

The division element nested within a select tag

HTML: <div class="row"> <div class="form-group"> <div class="col-xs-10"> <label for="class_code_reservation">Class Code</label> <select type="text" class="form-control" id="class_code_reservation" na ...

Is there a method available for troubleshooting unsuccessful AJAX requests? Why might my request be failing?

Whenever I click on a button with the class "member-update-button," an alert pops up saying "got an error, bro." The error callback function is being triggered. Any thoughts on why this might be happening? No errors are showing up in the console. How can I ...

Converting a table into JSON format

I'm working on developing a live application that will showcase data in a table format like the one below: Machine Production Scanned Delta Mach 1 2500 1000 1500 Mach 2 1500 1300 200 Mach 3 6500 5000 1500 Mac ...

Choosing a checkbox by considering the checkbox value, especially in cases where the checkbox and its label are separate elements

My goal is to click on the checkbox located next to the label "Print Method 1". Take a look at how the element appears here Below is the HTML code for reference: <div class="texter"> <div class="checkbox"/> ...

Creating visually appealing websites is made easy with Bootstrap 5's innovative image and

I am working on a Bootstrap 5 website template and I want to add text with a white background in the center of an image. Instead of seeing just a white color over the image, I would like to have a white rectangle with a title and text centered on the imag ...

Utilizing icons with vuetify's v-select component: a guide

In the code snippet below, I am using a v-select element to display a list of items filled from an array: <v-select v-model="myModel" :items="users" chips :readonly="!item.Active" label="Required users to f ...

Incorporating Node.JS variables within an HTML document

After building a simple site using Express, I discovered that Node.js variables can also be used with Jade. exports.index = function(req, res){ res.render('index', { title: 'Express' }); }; This is the code for the index file: ext ...

Guide on adjusting the scroll position in tinyscrollbar on page load

I have integrated tinyscrollbar into my project. One of the options available is contentPosition (Number, indicating the position of the content relative). Yet, I am struggling to modify it as needed. This is how my current JavaScript code looks: $(do ...

What is the best approach in JavaScript (jQuery) to loop through every 'a' element on a webpage, sequentially applying a unique style to each one?

Imagine this scenario: On a webpage, there are multiple 'a' tags with different alt tag values: <a href="img1.jpg" class="myClass" alt="0,0,600,200"></a> <a href="img2.jpg" class="myClass" alt="200,0,600,75"></a> <a hr ...

The art of defining PropTypes for the style attribute in Reactjs

Is there a way to pass the 'style' attribute into my component using JSX syntax? <InputTextWithValidation id="name" style={{width:'100%'}} .../> I'm wondering how I should define the PropTypes for ...

Adding objects to an existing array in Vue.js can be a seamless and

Struggling to populate my existing array with elements from a JSON response using a button click. The issue lies in properly adding these elements to the array. I have an empty array named results where I store the data from the response. export default ...

Best Practices for Making Remote Requests in Ruby on Rails

Currently, I am creating a Single Page Application using Ruby on Rails for the first time. Although I am still learning, I have set up a side menu with links and a container on the right part of the page to display partial pages. An example of one of my me ...

Refresh the Vue page only once after it is mounted

Users should only experience the page refreshing once upon visiting. However, if I add location.reload() within the mounted() function, it causes an infinite loop of page reloads. ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

Sending values to Vuex getters from a Vuex action

I have been utilizing a Vuex getter across various components in my application. However, I recently encountered a scenario where I require slightly more intricate logic before accessing the getter, leading me to employ a Vuex Action. The challenge now is ...