Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the displayed div container appear beneath the other links when clicked? Additionally, I'd like to restrict only one link to be selected, but I'm not sure how to achieve that. I have limited experience with JavaScript and CSS so any help would be appreciated.

Most of the styling has been removed from my code for clarity, but here is the basic functionality:

#togglebox {
  display:none;
}

#togglebox li{
  display: inline-block;
}

#extrabox {
  display:none;
  background: #E6ECF2;
  text-align: center;
  min-width: 100%;
}

#extrabox li{
  display: inline-block;
}

#extrabox2 {
  display:none;
  background: #E6ECF2;
  text-align: center;
  min-width: 100%;
}

#extrabox2 li{
  display: inline-block;
}

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}

<ul class="sub-menu" style="display:inline;">
  <a href="#"><li id="NSM1">Normal Sub Menu</li></a></td>
  <a href="#" onclick="toggle_visibility('togglebox');"><li id="SMEL">Sub-menu Item with Second Level</li></a>
  <a href="#"><li id="NSM2">Normal Sub Menu</li></a>  
  <br />          
</ul>

<div id="togglebox">
  <a href="#"><li id="NSSL1">[Normal Link]</li></a>
  <a href="#" onclick="toggle_visibility('extrabox');"><li id="SSL2">[Has extra Level]</li></a>
  <div id="extrabox">
    <a href="#"><li id="sublinkea">3rd level item1</li></a>
    <a href="#"><li id="sublinkeb">3rd level item2</li></a>
    <a href="#"><li id="sublinkea">3rd level item3</li></a>
    <a href="#"><li id="sublinkeb">3rd level item4</li></a>                    
  </div>
                        
  <a href="#" onclick="toggle_visibility('extrabox2');"><li id="SSL3"><li id="sublinksc">[Has Extra Level]</li></a>
                                
  <div id="extrabox2">
    <a href="#"><li id="sublinkea">3rd level item1</li></a>
    <a href="#"><li id="sublinkeb">3rd level item2</li></a>
    <a href="#"><li id="sublinkea">3rd level item3</li></a>
    <a href="#"><li id="sublinkeb">3rd level item4</li></a>                    
  </div>
  
  <a href="#"><li id="NSSL2">[Normal Link]</li></a>
</div>

Answer №1

It seems like the issue lies in having #extrabox nested within #togglebox as a child when it should be a sibling. This arrangement causes #extrabox to impact the positioning of any block-level elements that follow it under #togglebox. To resolve this, consider the following adjustment:

<div id="togglebox">
  <ul>
    <li id="NSSL1">
      <a href="#">[Normal Link]</a>
    </li>
       // Updated for better element structure
    <li id="SSL2">
      <a href="#" onclick="toggle_visibility('extrabox');">
        [Has extra Level]
      </a>
    </li>
  </ul>
</div>
// Revised placement to address display issues
<div id="extrabox">
  <!-- place #extrabox contents here -->
</div>

(Additionally, I have corrected the nesting of the a tags within the ul; only li tags are valid children of ul.)

Similarly, ensure that #extrabox2 is moved outside of #extrabox to prevent disturbance to its sibling elements.

If you could provide clarification on your statement "Also I would like to make it where only one link can be selected," I would be glad to assist further.

I hope this information proves helpful!

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

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

React: troubleshooting error of empty object displayed by console log

Just diving into the world of React and facing a challenge with importing a list of objects from a JS file to set them as the initial state of my app. Here's what I've tried: import allSamples from './reducers/reducerSamples'; var App ...

Tips for showcasing the elements depending on the chosen category

Here is a Vue.js code with multiple templates associated with multiple components. The goal is to display each component based on the selected category. For example, if "single family homes" is selected from the dropdown menu, the "step2" component shoul ...

Sending JavaScript/jQuery variables to a different PHP page and navigating to it

For a while now, I've been working on: Executing a .js file on the client side (successful). Passing the returned object (the variables returned) as an array to another php page for further processing (successful but with issues). The first point, ...

Ways to connect to an element's data- attribute

I am working with a data attribute that looks like this: <a href="stuff" data-open-dialog="location-XXXX">click</a> <a href="stuff" data-open-dialog="location-YYYY">click</a> How can I bind to the data-open-dialog and extract the ...

Grid with a column range of 1 to 3 should be used

My website currently features a grid that can have anywhere from 1 to 3 columns. To ensure flexibility in the number of columns, I am using auto-fit: .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min-content, 1fr)); gap: 40px; ...

Why is AJAX failing to execute PHP file from JavaScript?

The Issue: Hello, I have confirmed that my PHP file is functioning properly. However, the AJAX code connected to my JavaScript function seems to be malfunctioning. Even though the function is triggered, nothing happens as expected. The Script: Check o ...

When using AngularJS, the templateUrl feature delays the initialization of the controller, causing issues with dependent code

Recently, I began experimenting with AngularJS and so far, everything seems to be going smoothly except for one small issue. Let's consider a scenario where I have two directives, with one directive relying on the other, like this: angular.module(&ap ...

Extracting targeted information from an HTML page using Python: A step-by-step guide

I'm a beginner in python and I need to scrape information from an HTML text file using python 2.7. The example below shows the structure of one firm's data in the HTML file. The same structure is used for all other firms as well, with each firm ...

Use jQuery to target an element by its class name and node index

I am trying to target a specific element with the class ".myclass" by its node index, but I keep encountering an error stating that the element has no "animate" function. Here is an example: <div class="myclass"></div> <div class="myclass" ...

Adding and Removing Attributes from Elements in AngularJS: A Step-by-Step Guide

<input name="name" type="text" ng-model="numbers" mandatory> Is there a way to dynamically remove and add the "mandatory" class in Angular JS? Please note that "mandatory" is a custom class that I have implemented. Thank you. ...

Looping through multi-dimensional JSON objects with jQuery

Hello there, I'm currently facing some challenges in getting the screen below to work properly: Project progress screen I have generated the following JSON data from PHP and MYSQL. My goal is to display the project alongside user images and names whe ...

Require assistance with handling Ajax when a function with an Ajax call is repeatedly invoked

I am seeking guidance with ajax as I am still new to it. A problem arises when the same ajax call is made multiple times before the previous one completes its execution, resulting in an empty pop-up on the user interface. How can this issue be resolved? Es ...

Issue with integrating e-junkie shopping cart with Bootstrap 5

After transitioning from Bootstrap 4 to Bootstrap 5 and encountering navigation issues on smaller screens, I delved into the code to uncover the source of the problem. It turns out that the collapse button in the navbar wasn't functional due to confli ...

Is it possible to target the sibling of the currently selected or focused element with CSS?

I'm attempting to add button functionality to show and hide errors using CSS. By clicking the CSS button or link, I can target the siblings of the focused element as shown below. This method is only effective in IE8+ browsers. #ShowErrors:focus + a ...

Tips for controlling numerous tabSlideOUt tabs on a single webpage

Is there a way to implement multiple tabSlideOut functionalities on a single page, similar to the examples provided in the following links: source code on GitHub and Fiddle Example? Specifically, I am looking to have tabs that can be toggled, ensuring tha ...

Get information that has been uploaded using ajax

I need help with my code for sending data via ajax to an update.php page. $(document).ready(function() { $("#modify").click(function() { var a = $("#a").val(); var b = $("#b").val(); var c = $("#c").val(); $.ajax({ type: "POST", ...

Is it possible to have square corners on the Vuetify Mobile Drawer component?

Currently, I am working with the Vuetify mobile drawer component and my goal is to give it square corners instead of the default rounded corners that are prevalent in Material design for all Vuetify components. While the Vuetify card component offers a " ...

Sending form information through AjaxPassing information from a form using

Currently, I am working on a project where one page opens a thickbox of another page that contains a form. Once the form is submitted and data is written to the database, I need the parent page of the thickbox to update specific rows of the form that have ...

Incorporating a delete button onto an image using JavaScript

I am currently developing a BlogApp and facing difficulty in attempting to include a button on an image. The image is being retrieved from the Django database in JavaScript (HTML). My goal is to have a clickable button overlaid on the image. views.py def ...