Show and hide the responsive menu with a single click

I am currently working on creating a responsive menu. It is functioning properly, however, I am having trouble implementing an onclick effect in CSS. At the moment, I am using a hover effect. How can I make it so that when the screen width is less than 750px, clicking on the menu in picture number 2 (ul) will display the menu from picture number 3 (li)? This is a one-page site, so when I click on an element from the drop-down menu, it should hide the menu again (li).

HTML:

<header>
    <nav id="menu">
        <ul>
            <li class="li"><a href="#">WITAJ</a></li>
            <li class="li"><a href="#">O MNIE</a></li>
            <li class="li"><a href="#">DOŚWIADCZENIE</a></li>
            <li class="li"><a href="#">CO ROBIĘ?</a></li>
            <li class="li"><a href="#">KONTAKT</a></li>
            <li><a href="#">MOJE PRACE</a></li
        ></ul>
    </nav>
</header>

CSS:

@media screen and (max-width: 750px) {      
    header nav#menu ul:hover > li{
        display:block !important;
    }

    header nav#menu ul li{
        display:none !important;
    }
}

Answer №1

Creating a click effect in CSS can be challenging, which is why many developers turn to JavaScript for assistance. One simple solution using jQuery is as follows:

$(function() {
  var menuVisible = false;
  $('#menuBtn').click(function() {
    if (menuVisible) {
      $('#myMenu').css({'display':'none'});
      menuVisible = false;
      return;
    }
    $('#myMenu').css({'display':'block'});
    menuVisible = true;
  });
  $('#myMenu').click(function() {
    $(this).css({'display':'none'});
    menuVisible = false;
  });
});

This code snippet not only displays the menu when the button is clicked but also hides it when a menu item is selected.

In CSS, manipulating visibility based on screen size requires media queries. Take a look at this example.

Here is the HTML structure for this demonstration:

<div id="menuBtn">click me</div>
<nav id="myMenu">
  <ul>
    <li>entry 1</li>
    <li>entry 2</li>
    <li>entry 3</li>
    <li>entry 4</li>
  </ul>
</nav>

Check out the live example on jsFiddle.

Answer №2

Here's an alternative approach for achieving the same effect:

$(document).ready(function(){
    $('#menu').click(function(){
        $('#menu ul').toggle();
    });
});

Answer №3

Have you considered using JavaScript in this way:

$(document).ready(function(){
  $("#button").click(function(){
$("#panel").slideToggle("slow");
  })
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button">BUTTON ▾ </div>
<div id="panel">
<form name="form" action="{{ url_for('submit_form', form='Panel') }}" method="post">
{{ panel.content }}
<div id="submit"><input type="submit" value="Submit"></div>
</form>
</div>
</div>

This code will show the button panel and when clicked, the panel will slide out.

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 spread operator in Vuex is causing compilation errors with babel, as it continuously results in a module build failure

Currently, I am utilizing a spread operator within my mapGetters object. It is crucial to use a specific babel-preset-stage for proper ES6 compilation. Even after installing babel-preset-stage-2 via npm, I encountered the following error: ERROR in ./~/bab ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

Tips for creating a nodeCategoryProperty function for a TypeScript Model:

nodeCategoryProperty function has a signature requirement of (a: ObjectData, b?: string) => string. In my opinion, this should be updated to (a: ObjectData, b?: string) => string | void, as the function is intended to not return anything if used as a ...

Mocking functions using Sinon and Asynchronous calls

I am working on a project where I have a file called mainFile that utilizes a method named helperMethod. This method, which resides in a separate file called helperFile, returns a Promise. How can I mock the output of the helperMethod? Here is the structu ...

Insufficient module names remaining in NPM

Starting to release modules on NPM has been on my mind, but I can't help but worry about the limited availability of sensible module names in the public domain. Is there a way to create a public NPM module that organizes all my module names within a ...

Transfer me to Mobile, please

Is it possible to redirect users to mobil.navn.dk when they log on from a mobile device such as an iPhone, iPad, or other smartphones? If accessing the site from a browser, users should not be able to log in on navn.dk. I've attempted to achieve this ...

Guide on accessing a node within the firebase database

My goal is to allow each user to choose a total of 6 players. When a player is selected, their player ID is sent to a node on the database called 'total' using the push() method. The code snippet is provided below: var ref = firebase.database() ...

Exploring the world of AngularJS and Packery

After stumbling upon this particular question, I was thrilled to find the perfect answer that suits my needs. Now I am seeking guidance on how to implement the solution provided in this question. Is there a way to make the necessary changes for utilizing n ...

Is there a way to programmatically open the menu Options on Synology-NAS DSM using JavaScript, jQuery, or EXTJS code?

Currently, I am working on automating some tasks on a Synology NAS using JavaScript. It appears that the web-based operating system DSM was built with Ext JS 3.X. An interesting observation is that while the "Main Menu" can be triggered to open by simulat ...

What is the best way to retrieve a list of unchecked checkboxes in a Razor Page model?

Currently, I am working on a razor page using .NET Core 7. I have encountered an issue where I am unable to pass values of 1, 2, and 3 for unchecked checkboxes from the HTML page to the page model in the post method. When the user clicks the submit button ...

Issue with Brave browser: CSS animations not functioning properly, although they work perfectly in Firefox

Link to Codepen: https://codepen.io/sabeser/pen/RwYzJpd HTML: <div id='wrapper'> <div class='circle'></div> <div class='circle'></div> </div> CSS: :root { --scale--rati ...

Alignment of input fields and labels in Bootstrap by utilizing the Grid System

Currently, I am in the process of developing a form that includes multiple input fields. To organize these fields, I have utilized the Bootstrap 4 Grid system. However, I am encountering challenges when it comes to aligning certain input fields. Snippet ...

Tips for successfully passing the selected dropdown value into contextscope within AngularJS

Hey there! I currently have a dropdown list featuring various animals. Here is the code snippet: $scope.animals = [ {value:'lion', name:'lion', description: 'lion'}, {value:'cat', name:'cat', ...

The child element nudges the parent div, causing a noticeable gap within the parent container

I am facing an issue with my div structure. Within the main div, I have another nested div and within that, there is one more nested div. My goal is to make the last div appear to float outside of both parent divs, like a badge sticking out of the main div ...

Just getting started with jQuery and looking for assistance with adding elements during events

My current project involves creating a button that, when clicked, updates a 'feed' div. The goal is to generate three elements: a tweet(<div>), a message(<p>), and a username(<p>). These elements should be added to the tweet div ...

Tips and Tricks for Uploading Images with React, fetch, and Django REST

Currently facing a roadblock in my development work. Attempting to upload a photo through FormData in fetch, but running into issues with the content header or backend handling. Need some assistance troubleshooting this problem. general.js - Handler for r ...

Demonstrate the Current Cursor Location on a Web Element with the Help of jQuery and PHP

Can the cursor position in an element, such as class="board", be shared with others to display it as a translucent circle or similar indicator? Is it feasible to retrieve the cursor position using jQuery? Is it achievable to transmit the cursor positio ...