Dynamically generating subitems for a menu

I have created a Menu using CSS/Bootstrap in my asp.net application, but I need the submenus to be generated dynamically based on the user's role at runtime. Does anyone have any suggestions on how I can achieve this? I am looking for ideas on how to create subitems dynamically on the website. Any help would be greatly appreciated.

view image description here

Answer №1

You have the ability to dynamically generate a sub-menu, and this is just one of the many methods to do so.

In my example, I've deliberately avoided using Bootstrap to showcase what's happening behind the scenes. Feel free to customize the class for sub-menu-items to align with your preferences and Bootstrap.

Be creative with your styling choices. I've kept it simple in this demonstration.

const menuItem = document.querySelectorAll(".menu-item");
menuItem.forEach((mi) => {
  mi.addEventListener("click", (e) => {
    const nextSibling = e.target.nextElementSibling;
    nextSibling.classList.toggle("hide");
  });
});

function addSubMenuItem(menuItemId, smi) {
  const menuItem = document.querySelector(`#${menuItemId}`);
  const sibling = menuItem.nextElementSibling;
  smi.forEach((subMenuItemName) => {
    const li = document.createElement("li");
    li.classList.add("sub-menu-item");
    li.textContent = subMenuItemName;
    sibling.append(li);
  });
}

addSubMenuItem("home", ["a", "b", "c"]);
addSubMenuItem("blog", ["a"]);
addSubMenuItem("work", ["a", "b", "c", "d", 1, 24]);
addSubMenuItem("about", ["a", "b", "c", 0, 83, 93]);
.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: relative;
  background-color: red;
}

.menu-item-container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.menu-item {
  padding: 1rem;
  cursor: pointer;
  user-select: none;
}

ul.sub-menu {
  display: inline-block;
  list-style-type: none;
  top: 100%;
  background-color: royalblue;
  position: absolute;
  padding: 0;
  margin: 0;
}

li.sub-menu-item {
  padding: .25rem 1rem;
}

.hide {
  display: none !important;
}
<div class="container">
  <div class="menu-item-container">
    <div class="menu-item" id="home">Home</div>
    <ul class="sub-menu hide">
    </ul>
  </div>
  <div class="menu-item-container">
    <div class="menu-item" id="blog">Blog</div>
    <ul class="sub-menu hide"></ul>
  </div>
  <div class="menu-item-container">
    <div class="menu-item" id="work">Work</div>
    <ul class="sub-menu hide"></ul>
  </div>
  <div class="menu-item-container">
    <div class="menu-item" id="about">About</div>
    <ul class="sub-menu hide"></ul>
  </div>
</div>

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

Switching from a layout of 3 columns to 2 columns on iPad when orientation is changed to portrait

Apologies for posting this inquiry here, but I am facing a challenge with an iPad issue when switching to portrait orientation on my website. I am using a @media query to detect the portrait view and I want to switch from three columns to two. However, th ...

Utilize jQuery to toggle the visibility of a div depending on the numerical quantity input

I would greatly appreciate any assistance with this request, please. Here is the input that I have: <input onchange="UpdateItemQuantity(this.value,1284349,0,10352185,2579246,'','AU'); return false;" type="number" class="form-contro ...

Ways to customize background color for a particular date?

I have been using the fullcalendar npm package to display a calendar on my website. I am trying to figure out how to set a background color for a specific selected date. I tried looking into this issue on GitHub at this link. However, it seems that dayRe ...

Guide to updating the background color of an element with AngularJs when clicked

I've used AngularJS's ng-repeat to display a list of <div> elements. When I select one <div> (div1), its background color changes to blue. If I then click on another <div> (div2), div1's background returns to white and div ...

Why does the map function in JavaScript not allow for a function argument?

I encountered an issue while calling a function and passing an array of objects as the first argument, with the second argument being an object property of the first argument. Strangely, the map function was not accepting the second argument property. He ...

Is there a way to handle an error or display N/A when an object is not found in the JSON data I am working with?

Today's games lineup and broadcasting channels can be displayed using this JSON format. However, I am encountering the following error: TypeError: /home/ubuntu/workspace/sportsapp/views/results.ejs:8 6| <% data["games"].forEach(function(game){ ...

JQuery click event does not play nicely with Javascript array splice functionality

When using for loops, I noticed that array.splice doesn't seem to be working as expected. The array remains unchanged. I tried moving things around and found that it still doesn't work in Chrome. var menu =['#men','#wmen',&a ...

Creating a dynamic image viewing experience similar to Facebook's image viewer using jQuery

Here are two div tags that show the previous and next images from the large image collection: <div class="alignleft"><a href="1005.php"><img width="50" height="50" src="thumb-98.jpg" class="previous"></a></div> <div class ...

Columns nested within tabs in Bootstrap4

My current layout is shown here: https://i.sstatic.net/vQsqz.jpg I am looking to incorporate nested columns within these tabs. My attempted solution so far has been unsuccessful. The issue I am facing is that the columns within the specific tabs are ove ...

Encountering a 404 error while using THREE.ImageUtils.loadTexture in three.js

My first attempt at using three.js involves loading a 3D model, but I'm encountering an issue with texture loading. loader.load('models/asteroid_OBJ/asteroid OBJ.js', function (geometry, materials) { var material = new THREE.MeshLambertM ...

Using jQuery, retrieve JSON data from a different domain URL, even if the JSON data is not well-structured

Currently, I am utilizing jQuery's ajax function to access a URL from a different domain which returns JSON data. During my testing phase, I've encountered an issue where the presence of multiple '&quot' strings within the JSON valu ...

An unexpected 'undefined' occasionally tacked onto 1% of the URLs visitors requested on my website starting from June 12, 2012

Ever since June 12, 2012 at 11:20 TU, I have been noticing strange errors in my varnish/apache logs. At times, after a user has requested a page, I observe a similar request moments later but with the URL string after the last "/" being replaced by "undef ...

retrieving a promise fails during the set interval

Hey there! I'm currently a computer science student and still getting the hang of things. Recently, I encountered an issue that I can't seem to solve on my own. The problem is related to fetching data from my MongoDB database every few seconds an ...

jquery malfunctioning in an html5 document

I recently tried to create a scrolling marquee using code I found on lynda.com, but it isn't working properly on my HTML5 page. The main issue I've identified so far is that the code includes a reference to an XHTML 1.0 Transitional document type ...

Having trouble locating the source of the issue causing the product page to appear too wide on Shopify

Can someone assist me in identifying the issue that is causing the product page on this website () to be too wide? Here is an image highlighting the issue. I made some CSS customizations to make the product gallery full width and added padding to the pro ...

Validation in AngularJS - Setting minimum length for textarea using ng-minlength

I am currently tackling a project that heavily relies on AngularJS for the front-end. Here's what I am dealing with: The validation requirement I am aiming for is as follows: The Next button should remain disabled unless the reason provided is at le ...

The function jQuery.post is transmitting special characters encoded

After creating a string using recipeBlob = JSON.stringify(recipeData), I noticed that when sending it via $.post, the received data at my PHP script is showing up with escaped characters like this: {\"properties\":{\"Energy\":{\"v ...

Zooming does not activate the onZoom event

I have created a line chart using react-chartjs-2 and incorporated the chartjs-plugin-zoom plugin. My goal is to have the zoom level displayed in the console whenever the chart is zoomed in or out. However, it seems that the onZoom function is not being tr ...

Using JavaScript, you can add an article and section to your webpage

Currently, I am utilizing AJAX to showcase posts. My objective is to extract each property from a JSON object that is returned and generate an <article> for the title followed by a subsequent <section> for the content. While I can successfully ...

A guide to managing AJAX requests within Symfony 2

I'm looking to remove a set of sessions on a page using AJAX. Essentially, I want users to be able to click on a link and have the session removed without having to navigate to a new page. Additionally, I would like to display a message upon successfu ...