Expandable drop-down menu upon clicking

Having trouble creating a dropdown menu on click? Check out the real site I'm working on: . The menu turns into a single button under 736px width, but it's buggy on mobile devices. When clicked on a phone, it automatically redirects to the last button's "href" even if it's not visible. Also, the menu doesn't close after clicking the "home" button again.

I want to create a drop-up menu that stays in place when you click the button (instead of moving up like it does now) until clicked again. Any advice would be appreciated!

CODE:

<div class="navbar" id="myTopnav">
    <div class="dropup">
        <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <img src="images/Icons/home.png" />  </a>
        <div class="dropup-content" >
            <a href="#home" >   <img src="images/Icons/home.png" /> Home</a>
            <a href="#news">    <img src="images/Icons/about.png" /> News</a>
            <a href="#contact"> <img src="images/Icons/info.png" /> Contact</a>
            <a href="#home">    <img src="images/Icons/menu.png" /> Home</a>
            <a href="#news">    <img src="images/Icons/pic.png" /> Newssssssssssss</a>
            <a href="#contact"> <img src="images/Icons/about.png" /> Contact</a>
       </div>
    </div>
</div>

SCRIPT (revised script to address the issue with closing from a mobile device):

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches('.icon')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

Answer №1

UPDATED:

To start, the HTML code you provided does not include a myDropdown element. Therefore, the first step is to add that id to the dropup-content element. Subsequently, we can simply toggle the class of show when the a (or icon) is clicked. Here is the modified code:

HTML:

<div class="navbar" id="myTopnav" >
     <div class="dropup">

                    <a class="icon" onclick="myFunction()"> <img src="images/Icons/home.png" />  </a>

           <div class="dropup-content" id="myDropdown">
                        <a href="#home" >   <img src="images/Icons/home.png" /> Home</a>
                        <a href="#news">    <img src="images/Icons/about.png" /> News</a>
                        <a href="#contact"> <img src="images/Icons/info.png" /> Contact</a>
                        <a href="#home">    <img src="images/Icons/menu.png" /> Home</a>
                        <a href="#news">    <img src="images/Icons/pic.png" /> Newssssssssssss</a>
                        <a href="#contact"> <img src="images/Icons/about.png" /> Contact</a>
           </div>
     </div>
</div>

JAVASCRIPT:

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show")
}
// The above function toggles the menu on/off without the need for an additional loop.

Remember to customize the appearance of the show class in your CSS according to your preferences. To keep the menu fixed in position, apply position: absolute in the CSS with desired coordinates using top/left/right/bottom, and assign a z-index: 2(or higher) to ensure its visibility over other elements. I hope this resolves any lingering concerns.

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 drag-and-drop application failed to upload a video using Ajax

I am currently working on an application that allows users to upload files to a server with a drag and drop function. The app is functioning well for images, but occasionally encounters issues when trying to upload videos. I'm not certain if there&apo ...

Synchronize the currently chosen option between the radio button and dropdown menu

Issue Summary I am working with two forms - one with Radio Buttons and one with Dropdowns (select). Both have a similar structure where changing the value of one element should reflect in the other. Constraints: The ID and name attributes of each radi ...

Show all entries belonging to a specific ID on individual rows for each ID using PHP

I have a table generated from inner joins that displays different articles associated with outfit IDs. id_outfit | name | article ---------------------------------------- 56 | one | shoe.png 56 | one | dress.png 56 | one ...

Two entities positioned on opposite extremes

Is there a way to design a div with two elements (text and image) positioned on opposite sides? The length of the text varies as it's a list of months for selection. Ideally, the text should appear on the left side of the div as a "p" element, while t ...

Using jQuery to create overlapping images

Currently, I am working on an effect that involves overlapping images. The idea is that when a bar is clicked and dragged, the image underneath should reveal by adjusting its width. While my code functions, there are some glitches present. One issue is tha ...

What is the operational mechanism behind drag and drop page builders?

I am currently delving into my inaugural MERN project, where the functionality requires specific components (such as a checkbox to-do list, images, text, etc...) that empower users to construct various pages, larger multi-checkbox aggregation lists, and be ...

Angular factory transforming service

I am looking to transform the 'i18n' function into a factory in order to return a value instead of just setting it. Any suggestions or tips would be greatly appreciated! services.factory('i18nFactory', function() { var language = ...

What is the best way to create a tree structure in jQuery for organizing parent-child relationships within an unordered list (

Before <ul> <li parent-id="0" li-id="16">Anthropology Department</li> <li parent-id="16" li-id="18">Anthropology Faculty Collections</li> <li parent-id="16" li-id="23">Shared Collections</li> <li parent-id="0" ...

What is the best way to prevent "escaping" in the createTextElement method when using Javascript?

Check out the Jsfiddle demo document.getElementById("container").appendChild(document.createTextNode('&#xe145; ')) <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet> <div id="container" class="ma ...

Error: React.js - The specified element type is invalid

After setting up routing using react-router and trying to access the URL, I encountered an error message saying "Element type is invalid." Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for compos ...

Extension for Chrome

My goal is to develop a Chrome extension that, when a specific button in the extension is clicked, will highlight the current tab. However, I'm encountering some challenges. Currently, I have document.getElementById("button").addEventListen ...

I am having trouble having a select component populate with new child components while still maintaining its original value

So here's the situation. Let me simplify things for you. I'm in the process of developing an app that generates JSON queries to be sent to a server. The query-building components are structured in a nested manner: QueryContainer > QueryGroup ...

Tips for sending all form elements via ajax without explicitly mentioning their names

I'm developing an application with a dynamic form generation feature. When a button is clicked, I need to send all the form elements to another page using Ajax. The challenge is that since the form is generated dynamically, I am unable to specify elem ...

The jQuery's load function appears to be malfunctioning

$toolTip_inner.load('ajax/fetchUser_data.php',{ id: $tooltipText }); I am attempting to load the content of a PHP file into the toolTip_inner element while passing some parameters. The fetchUser_data.php file executes a MySQL statement and retr ...

Incorporate external visuals into printed materials

When a page is printed, a heading should be accompanied by an image to the right. I have defined the following stylesheet: @media print { h1::after { content: url( IMAGE_URL_HERE ); position: absolute; top: 0; right: 0; } } The issue ...

Encountered issue with Ajax post request without any additional details provided

I could really use some assistance with this issue. It's strange, as Chrome doesn't seem to have the same problem - only Firefox does. Whenever I submit the form, Ajax creates tasks without any issues. My MySQL queries are running smoothly and I& ...

Using Jquery to create a loop upon clicking

I'm currently implementing Jquery functionality to submit a form. My goal is to iterate through the form once the user clicks on the submit button in order to retrieve the selected option from various select fields that have been dynamically generated ...

Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original. Check out my code below: window.onload = function() { ImageObjSketch = new Image(); // URL ImageObjSketch.src = 'https://i.imgur.com/75lATF9 ...

Initiate the Photoswipe gallery with a single click of a link

I am currently using the photoswipe plugin on my website. I have set up some options and initialized it with a group of images. (function(window, PhotoSwipe){ document.addEventListener('DOMContentLoaded', function() { var options = { ...

Retrieve the current date and time in JSON format using moment.js for the local

Below is the code snippet I am working with: var startTime = moment("2020-09-08 16:00:00").toDate(); console.log(startTime) const data = {start: startTime} console.log(JSON.stringify(data) After running it, the result is as follows: Tue Sep 08 ...