Design an Expandable Menu for Mobile Website using Jquery and CSS

After diving into designing a mobile website using media queries and exploring various websites, it seems like accordion navigation menus are the popular choice. I've scoured the internet for an accordion walkthrough but haven't found one that explains it clearly enough.

An exemplary implementation can be seen on the Microsoft website. Here's my current code snippet:

<!DOCTYPE html>

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
<style>
    body {
padding: 0;
margin: 0;
}

#topMenu {
height: 50px;
width: 100%;
background-color: #cde;
display: block;
}

nav {
width: 100%;
height: auto;
display: block;
margin: 0;
padding: 0;
}

nav a {
text-decoration: none;
padding-left: 40px;
}

nav ul {
list-style: none;
display: block;
margin: 0;
padding: 0;
background-color: #ccc;
} 

nav ul li {
display: block;
width: 100%;
padding: 20px 0px 20px 0px;
border-top: 2px solid #abc;
}

nav ul ul {
height: 0;
overflow: hidden;
padding-top: 0px;
}

nav ul ul li a {
padding-left: 100px;
}
</style>
</head>

<body>

<div id="topMenu"></div>
<nav>
<ul>
<li><a href="">Link</a></li>
<li><a href="">Link</a>
<ul>
<li><a href="">Link 1</a></li>
<li><a href="">Link 2</a></li>
<li><a href="">Link 3</a></li>
<li><a href="">Link 4</a></li>
<li><a href="">Link 5</a></li>
<li><a href="">Link 6</a></li>
<li><a href="">Link 7</a></li>
</ul>
</li>
<li><a href="">Link</a>
<ul>
<li><a href="">Link 1</a></li>
<li><a href="">Link 2</a></li>
<li><a href="">Link 3</a></li>
<li><a href="">Link 4</a></li>
<li><a href="">Link 5</a></li>
<li><a href="">Link 6</a></li>
<li><a href="">Link 7</a></li>
</ul>
</li>
<li><a href="">Link</a>
<ul>
<li><a href="">Link 1</a></li>
<li><a href="">Link 2</a></li>
</ul>
</li>
<li><a href="">Link</a></li>
<li><a href="">Link</a></li>
<li><a href="">Link</a></li>
</ul>
</nav>

</html>

These navigation bars contain submenus [nav ul ul] that expand when nav ul li is clicked. Does anyone have tips on creating a dropdown submenu upon click or assistance with modifying the code?
I hoped to find a simple template that beginners could use and customize themselves.

Thank you for any guidance.

Answer №1

Forget about using Javascript - simply opt for a Checkbox instead. Take a look at this example: http://codepen.io/TimPietrusky/pen/CLIsl

If you still prefer to do it with Javascript, consider the following approach:

// assuming that nav-items triggering slidedown will have "#" as href
// while actual nav-items will have URLs
$('nav li a[href="#"]').on('click', function (e) {
    // prevent Click from redirecting
    e.preventDefault();
    // get the next ul after the clicked li a
    if ($(this).hasClass('visible')) {
        $(this).next('ul').slideUp(200).removeClass("visible");
    } $(this).next('ul').slideDown(200).addClass("visible");
});

CSS animation for transitioning height from 0 to auto won't work. Check out: How can I transition height: 0; to height: auto; using CSS?

Answer №2

Take a look at this

https://example.com/code-sample/1/

Unfortunately, CSS does not support click events directly; you will need to incorporate JavaScript and/or jQuery for this functionality. In the provided example, jQuery was utilized.

The solution involved adding a class hide-nav to the navigation element with the property display set to none. Additionally, a button was incorporated for user interaction.

A snippet of jQuery code was employed:

$(document).ready(function() {
    $('#topMenu-btn').on('click', function() {
        $('nav').slideToggle();
    });
});

Answer №3

Consider implementing a structure like the one below:

http://jsfiddle.net/kb668aag/

You may need to make some adjustments to the code provided.

    <div id="topMenu"></div>
    <nav>
        <ul>
            <li><a href="">Link</a></li>
            <li class="has_children"><a href="">Link</a>
                <ul class="sub-menu">
                    <li><a href="">Link 1</a></li>
                    <li><a href="">Link 2</a></li>
                    <li><a href="">Link 3</a></li>
                    <li><a href="">Link 4</a></li>
                    <li><a href="">Link 5</a></li>
                    <li><a href="">Link 6</a></li>
                    <li><a href="">Link 7</a></li>
                </ul>
            </li>
            <li class="has_children"><a href="">Link</a>
                <ul class="sub-menu">
                    <li><a href="">Link 1</a></li>
                    <li><a href="">Link 2</a></li>
                    <li><a href="">Link 3</a></li>
                    <li><a href="">Link 4</a></li>
                    <li><a href="">Link 5</a></li>
                    <li><a href="">Link 6</a></li>
                    <li><a href="">Link 7</a></li>
                </ul>
            </li>
            <li class="has_children"><a href="">Link</a>
                <ul class="sub-menu">
                    <li><a href="">Link 1</a></li>
                    <li><a href="">Link 2</a></li>
                </ul>
            </li>
            <li><a href="">Link</a></li>
            <li><a href="">Link</a></li>
            <li><a href="">Link</a></li>
        </ul>
    </nav>

CSS

body {
padding: 0;
margin: 0;
}

#topMenu {
height: 50px;
width: 100%;
background-color: #cde;
display: block;
}

nav {
width: 100%;
height: auto;
display: block;
margin: 0;
padding: 0;
}

nav a {
text-decoration: none;
padding-left: 40px;
padding: 20px 40px;
display: block;
}

nav ul {
list-style: none;
display: block;
margin: 0;
padding: 0;
background-color: #ccc;
} 

nav ul li {
display: block;
width: 100%;
border-top: 2px solid #abc;
}

nav ul ul {
overflow: hidden;
padding-top: 0px;
}

nav ul ul li a {
padding-left: 100px;
}

ul.sub-menu{
    display: none;
}
.has_children > a{
    color: #ddd;
}

JS:

var $menu_with_children = $('.has_children > a');

$menu_with_children.on('click', function(e){
    e.preventDefault();
    var $this = $(this);
    if (!$this.parent().find('> .sub-menu').hasClass('visible')) {
        $this.parent().find('> .sub-menu').addClass('visible').slideDown('slow');
    } else{
        $this.parent().find('> .sub-menu').removeClass('visible').slideUp('slow');
    }
});

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

Inserting items into the document after updating the list with fresh data

I populate an array of objects when a button is clicked. The array only has 10 objects initially, but users can add more after it's loaded into the DOM. Here's how I handle this: $scope.Information = []; $.each(data, function (i, v) { if ...

Swapping out the document.createElement() method for React.createElement()

In a JavaScript library, I utilize document.createElement() to create an HTMLElement. Now, I am looking to develop a React library with the same functionality. My initial thought was to substitute document.createElement() with React.createElement(). There ...

toggle the class on a label that contains a checkbox

Is there a way to use toggleClass to add a class to a label when clicked, even if the label contains a checkbox? Currently, I am having an issue where the class is only added when clicking directly on the checkbox. How can I make it so that the class is ad ...

Linking the Twitter social button to the originating page

Is there a way to link the Twitter button to a referrer URL, so that all tweets will refer back to the page the visitor came from instead of the landing page itself? I've been able to do this with Facebook and G+ by using a href within the script and ...

Is there a similar alternative to {useLocation} provided by 'react-router-dom' that can be used in Next.js?

import { useLocation } from 'react-router-dom'; Currently utilizing Nextjs, I'm seeking assistance in finding an alternative for useLocation ` import Link from 'next/link'; import { FC } from 'react'; import {useRout ...

How can we effectively streamline these if statements for better organization and efficiency?

Currently, I am dealing with a straightforward if condition structure and aiming to keep the code as DRY (Don't Repeat Yourself) as possible. I believe that I have achieved optimal dryness for my specific situation by utilizing object keys as pointers ...

Issue with Bootstrap: unable to align columns vertically

I am currently learning how to use bootstrap, but I am facing a challenge with vertical alignment of columns. Despite trying various methods, I can't seem to get the content to align anywhere other than the top. Even starting from scratch with code fr ...

Tips on duplicating an object within a React state without using references

In my React application, I have a state that contains several objects. I need to make a copy of the c: "value" field from the initial state before it gets replaced by the input value from e.target.value. The purpose behind this is to ensure that ...

Exploring Angular2: Implementing oauth2 with token headers

As someone who is new to Angular 2, I found that things were much simpler with interceptors in version 1.*. All you had to do was add them and suddenly your headers were available everywhere, making it easy to handle requests especially when dealing with i ...

I have successfully added an image to my CSS file, and it is appearing in Chrome's inspect feature. However, the image is not visible on the actual website

Here is the code snippet: .nav-link-apple { width: 1.6rem; background: 4.4rem; background: url(./Logo.jpg) center no-repeat; } Although the image I added can be seen in inspect on Chrome, it is not visible on the actual webpage. I have tried s ...

Is it possible to utilize MongooseArray.prototype.pull() in typescript?

A problem has arisen in Typescript at this specific line of code: user.posts.pull(postId); An error message I'm encountering states: Property 'pull' does not exist on type 'PostDoc[]' The issue seems to be related to the fac ...

Having trouble with submitting a form using jQuery?

I have created a form on my website: <form action="thanks.php" onsubmit="return false" class="submitForm"> ... Various input fields ... </form> Additionally, I have included a jQuery script: $(document).ready(function() { $("form.subm ...

Interactive Dropdown Menu Generation

Despite my expertise in programming languages like MySQL, PHP, JavaScript, jQuery, HTML, and CSS, the current issue I am facing does not relate to any of these. It essentially comes down to three key aspects: Creating a menu layout with clickable link op ...

Encountering the error message "Cannot GET /" in a NodeJS Express

I've been experimenting with various approaches to resolve this issue, ranging from app.use(express.static(__dirname + "public")) to res.render. It seems to function correctly in my terminal environment but fails when I try to access it locally. Can a ...

Tips for storing user information in Firebase using React?

Is there a better way to maintain user sessions in my app? I've noticed that every time a user signs up, if the page reloads, they are logged out. I've tried looking into persistence in the official documentation but I'm still confused about ...

Nodemon isn't functioning properly: nodemon isn't loading as expected

db.js const mongoose = require('mongoose'); const mongoURI = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"; const connectToMongoDb = ()=>{ mongoose.connect(mongoURI, ()=>{ ...

Animating the background of a div element using jQuery

I am facing an issue with the code snippet below that I have written. It doesn't seem to be working as expected and I'm curious if anyone knows why. The problem is that I have set a background color on the DIV, but when hovering over it, I want ...

Creating a customizable HTML template for JSON data representation

I have incorporated t.js as the template engine in my current project. How can I create a template for this specific JSON data structure? { data: [ { FirstName: "Test1", LastName: "Test11" }, { FirstName: "Test2", ...

Export Image as Json File

I am currently working on creating a browser extension and I am trying to figure out how to save images locally. My plan is to store the images in a json file, but I'm feeling quite lost on how to accomplish this. Below is the code I have so far, alth ...

Troubleshooting: Issues with Visual Composer and Jquery Animations not Functioning Properly

Having a visual composer installed on my Wordpress site, I encountered an issue where inserting an image or any element and applying animation from within visual composer would cause the page to go blank with no animations showing. After reaching out to t ...