Is there a way to transform a hover dropdown menu into a sidebar dropdown menu that can be clicked on mobile devices?

Currently working on enhancing the navigation menu of my website, and I have encountered a challenge with a dropdown sub-menu when viewed on mobile devices. In reference to w3Schools, I successfully implemented a hover-based sub-menu for desktop users.

However, two issues persist on mobile:

  • The primary concern is enabling a clickable functionality to open the menu. I attempted to find solutions for creating a toggle that works via click on mobile and hover on desktop, but lacking expertise in JavaScript makes it challenging. While experimenting with making the menu accessible through clicking both on desktop and mobile, I prefer maintaining the hover feature for desktop users.
  • Additionally, I aim to customize the menu display for mobile and tablet views. Rather than displaying as a popup like on desktop, I envision a block layout spanning the width of a popout sidebar. My attempts to style the menu differently resulted in an accordion-like dropdown, overlaying other list items instead of pushing them down.

Your assistance in addressing these issues would be greatly appreciated!

Here's the code snippet including a click-triggered menu for both desktop and mobile:

// Code for toggling between showing/hiding the dropdown content upon user clicks
function subOpen() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if clicked outside
window.onclick = function(event) {
  if (!event.target.matches('.sub-menu-link')) {
    var dropdowns = document.getElementsByClassName("sub-menu-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}


//Code for hamburger menu toggle
const menuBtn = document.querySelector(".menu-btn");
let menuOpen = !1;
menuBtn.addEventListener("click", () => {
  menuOpen ? (menuBtn.classList.remove("open"), menuOpen = !1, document.documentElement.style.overflow = "scroll", document.body.scroll = "yes") : (menuBtn.classList.add("open"), menuOpen = !0, document.documentElement.style.overflow = "hidden", document.body.scroll = "no")
})
...

Answer №1

Include the following snippet in your CSS file:

@media(min-width: 1025px){
.sub-menu:hover .sub-menu-content {
  display: block;
  }
  }

By adding this code, you ensure that the hover effect will function properly on desktop screens with a width greater than 1025px, allowing the sub menu to be displayed.

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 use of the readonly attribute in an <input> element prevents the widget

Attempting to utilize the https://github.com/Eonasdan/bootstrap-datetimepicker, but facing an issue where making the input field read-only also disables the date picker button, preventing access to the date picker widget. <div class="container"> ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

Creating an HTML table with colspan and rowspan using ng-repeat from a deeply nested JSON dataset

I'm working on creating a table layout shown in the attached image: Composite Class Routine Check out my progress so far in this Plunker demo: https://plnkr.co/edit/4WiWKDIM2bNfnmRjFo91?p=preview The JSON data I'm using is as follows: $scope. ...

Using JSON formatting with NVD3 charts

Is there a method to transform my JSON data into a format that NVD3 will accept for a multi bar chart? I have a template set up in NVD3 here: http://jsfiddle.net/hohenheim/6R7mu/5/ The JSON data I want to display is as follows: [{"date": 1396828800, "imp ...

Z-index malfunctioning - need to troubleshoot

Check out my website at Upon visiting the website on a PC, you'll notice that the navigation menu appears on the loader. Can anyone explain why this is happening? The only modifications I made to my CSS are: <style> .navbar-inverse { backg ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...

Collapse an array containing objects with nested objects inside

Similar questions can be found here and here, but I am struggling to modify the code provided in the answers to fit my specific needs due to its conciseness. The structure of my array of objects is as follows: [ { id: 1, someProp: &quo ...

"Presenting Invoice Information on an Invoice Template: A Step-by-Step Guide

Currently, I am working with Laravel 5.7 and VueJs 2.5.*, where I have a table of invoices. My goal is to create a new component that will display a specific invoice based on user selection, allowing them to view or print the chosen invoice. I am still ex ...

Is Flash compatible with Cache-Control & Expires headers across all web browsers?

Working on a Flash .swf file created by someone else without access to the source code can be a challenging task. It appears to have been developed in Flash 9/AS3, but the certainty is lacking. The configuration settings for this Flash file are loaded fro ...

Exploring the power of Angular JS promises through ng-repeat

My current project involves fetching latitude and longitude coordinates from a postcode using an API, then utilizing those coordinates to retrieve data on street level crimes near that location on a specific date through the UK police API. However, I have ...

transform minutes into DD:HH:MM format (not a date)

I have experimented with various functions I came across on different platforms but none of them provide me with an accurate output. I tried one variation of this code (converting minutes to hours and minutes): const convertMinsToHrsMins = (mins) => { ...

Create a circle at the point where two table cells intersect in an HTML document

How can I create a circular shape at the intersections of HTML tables? I am struggling to figure out a way to incorporate shapes into HTML tables. My goal is to achieve a design similar to the image shown below. I have attempted using text and spans, as we ...

Is there a method to construct this? It appears quite challenging to create the intricate lines

I want to achieve this specific layout, but I am unsure how to align the lines next to the boxes. Should I use display or position properties to accomplish this? Image illustrating my desired outcome ...

What is the method to utilize attributes from one schema/class in a separate schema?

Consider the scenario presented below: Base.ts import Realm from 'realm'; export type BaseId = Realm.BSON.ObjectId; export interface BaseEntity { id?: BaseId; createdAt: string; updatedAt: string; syncDetails: SyncDetails; } e ...

The touch events are not detected on Pixi.js when buttons are placed on a stage that has been both scaled and

Currently, I am developing a game using pixi js. In order to ensure that the game appears consistent on all screens, I have implemented the following scaling logic: this.scale = Math.max(this.viewWidth, this.viewHeight) / (2048 * this.ratio); Additionall ...

How to position a <div> in the center of a popup <div>

I've encountered a problem trying to center a <div> within another <div> that pops up when a button is clicked. It's not my code, but it's similar. Here is the HTML: <div class="popup"> <div class="options"> ...

Navigating the carousel doesn't have to be complicated using Onsen-UI, especially when you want to

Currently, I am utilizing Onsen-ui along with angularjs. My issue lies in attempting to center images within a carousel, as they consistently align to the left. Below is the code snippet that I am working with: <ons-carousel direction="horizontal" styl ...

Guide on implementing the recently established attribute ID using jQuery

In my code snippet, I am assigning a new id to a button. Here is the code: $("#update").click(function(){ $("#update").attr('id', 'cancel'); }); After changing the id, I want to make it functional again in jQuery by reverting it b ...

What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this: const weekdays = eachDay.map((day) => format(day, 'EEE')); let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' }; w ...

What is the best method for looping through a JavaScript object in cases where the value itself is an object?

Updated query. Thanks to @WiktorZychla for sparking my Monday morning thoughts on recursion. The revised code is functioning correctly now. Assuming I have a dummy object structured like this: const dummy = { a: 1, b: 2, c: { d: 3, ...