Problem with the appearance of the drop-down menu

After a few dedicated weeks on a Web application project, I am currently tackling the challenge of a drop-down menu. Despite its functionality, there are two specific points I need help with:

  • When expanding the menu by selecting a main item, I want to prevent the green color from expanding to the sub-menu level, such as avoiding a green block from appearing below other sub-menus like "Menu2" and "Menu3" when "Menu1" is clicked.
  • Additionally, I aim to increase the size of the menu items. However, applying "padding: 14px 16px;" to the #menu li in the CSS code results in misalignment of the sub-menu items.

Would appreciate any guidance on resolving these issues. Thank you!

Stéphane

Presented below is the provided code snippet:

$(function() {
// Hide sub-menu:
$(".subMenu").hide();
// Hide elements of the screen:
$("#B3 th, #B3 td").hide();
$("[id^='B4_']").hide();
$("[id^='B5_']").hide();
// Hide/Display sub-menu once menu item is clicked:
$( ".mainlink" ).click(function() {
$(".subMenu").hide(); 
...

Note: The rest of the code has been omitted for brevity.

Answer №1

Trying to use position:absolute or relative in this scenario won't be effective as it will cause the menu to overlap with the buttons.

Instead, I have transferred most of the styling from the <li> elements to the <a> elements. This allows the <li> to expand with the subMenu and keeps the height (and green background) of the <a> unaffected.

I attempted to simplify the JavaScript and CSS by moving some style that was manipulated by JavaScript back into the CSS. I also updated the code to use the newer .on('click') syntax and utilized an HTML data attribute to connect the <a> to the button, eliminating the need to constantly find elements.

// Avoid repetitive search using jQuery
var menuAnchors = $('#menu > li > a'); // store top level anchors
var buttons = $("input[id^='B5_']"); // store all buttons

// Create a single click handler for all #menu > li > a
$('#menu').on('click', '> li > a', function() {
  menuAnchors.css('background-color', ''); // reset red to green
  this.style.backgroundColor = 'red'; // set anchor elements to red background when clicked

  $(".subMenu").hide().reset(); // hide all subMenu items
  $(this).next(".subMenu").toggle("slow", function() {}); // display the nearest next subMenu
});

// Create a single click handler for all .subMenu anchors
$('.subMenu').on('click', function(e) {
  $(this).reset();
  e.target.style.backgroundColor = 'red'; // set target anchor to red
  var buttonId = $(e.target).data('button'); // retrieve buttonId from data attribute
  $('#' + buttonId).show();
});

// Custom function to hide buttons and reset background to orange
$.fn.reset = function() {
  buttons.hide(); // hide all buttons
  $(this).find('a').css('background-color', ''); // reset red to orange
  return $(this);
}
body {
  background-color: #3e8cbd;
}

ul {
  display: flex;
  list-style-type: none;
  padding: 0;
}

#menu li {
  width: 10em;
  color: white;
  text-align: center;
}

#menu li a {
  display: block;
  padding: 14px 16px;
  cursor: pointer;
  background-color: green;
  border-right: 1px solid #bbb;
  border-top: 1px solid #bbb;
}

#menu li:last-child a {
  border-right: none;
}

.subMenu {
  flex-direction: column;
  padding: 0;
  display: none;
}

#menu .subMenu a {
  background-color: orange;
}

#B5 input {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
  <li>
    <a class="menuLink">Menu1</a>
    <ul class="subMenu">
      <li><a data-button="B5_1">Sub-Menu1-1</a></li>
      <li><a data-button="B5_2">Sub-Menu1-2</a></li>
    </ul>
  </li>
  <li>
    <a class="menuLink">Menu2</a>
    <ul class="subMenu">
      <li><a data-button="B5_3">Sub-Menu2-1</a></li>
      <li><a data-button="B5_4">Sub-Menu2-2</a></li>
      <li><a data-button="B5_5">Sub-Menu2-3</a></li>
    </ul>
  </li>
  <li>
    <a class="menuLink" onClick="alert('Development of the Menu3 functionalities postponed!')">Menu3</a>
  </li>
</ul>

<table id="B5">
  <tr>
    <td>
      <input id="B5_1" type="button" value="Button1" onClick="alert('Action 1')">
    </td>
    <td>
      <input id="B5_2" type="button" value="Button2" onClick="alert('Action 2')">
    </td>
    <td>
      <input id="B5_3" type="button" value="Button3" onClick="alert('Action 3')">
    </td>
    <td>
      <input id="B5_4" type="button" value="Button4" onClick="alert('Action 4')">
    </td>
    <td>
      <input id="B5_5" type="button" value="Button5" onClick="alert('Action 5')">
    </td>
  </tr>
</table>

Answer №2

  1. Using position absolute for the submenu and position relative for the #menu li
  2. Ensuring no more submenu items shifting due to the implementation in point 1

Check out the demo here

#main li {padding: 14px 16px; position:relative;}
.subMenu {position:absolute;top:100%;left:0;}

Answer №3

Hey there, make sure to update the CSS and JS code below in your project for the desired outcome:

$(function() {
// Hide sub-menu:
$(".subMenu").hide();
// Hide elements of the screen:
$("#B3 th, #B3 td").hide();
$("[id^='B4_']").hide();
$("[id^='B5_']").hide();


// Hide/Display sub-menu once menu item is clicked:
$( ".mainlink" ).click(function() {
$(".level1").css("background-color","green");
$(".level2").css("background-color","orange");  
$(this).parent().css("background-color","red");
 $(this).parent("li").find(".subMenu").slideToggle( "slow", function() {
// Animation complete.
});

});

// Hide/Display elements of the body of the screen once sub-menu item is clicked:
// Request/Create
/*
$( "#item1_1" ).click(function() {
$(".subMenu li").css("background-color","orange");
$(this).parent().css("background-color","red");
$("[id^='B5_']").hide();
$("[id='B5_1']").show();
});

// Request/Search
$( "#item1_2" ).click(function() {
$(".subMenu li").css("background-color","orange");
$(this).parent().css("background-color","red");
$("[id^='B5_']").hide();
$("[id='B5_2']").show();
});
// Folder/Report/Create folder
$( "#item2_1" ).click(function() {
$(".subMenu li").css("background-color","orange");
$(this).parent().css("background-color","red");
$("[id^='B5_']").hide();
$("[id='B5_3']").show();
});
// Folder/Report/Create report
$( "#item2_2" ).click(function() {
$(".subMenu li").css("background-color","orange");
$(this).parent().css("background-color","red");
$("[id^='B5_']").hide();
$("[id='B5_4']").show();
});
// Folder/Report/Search
$( "#item2_3" ).click(function() {
$(".subMenu li").css("background-color","orange");
$(this).parent().css("background-color","red");
$("[id^='B5_']").hide();
$("[id='B5_5']").show();
});
*/
});
header {
border-style: solid;
margin: 0;
}

footer {
border-style: solid;
margin: 0;
}

#menu ul {
display: block;
    list-style-type: none; 
    padding: 0;
}

#menu li {
width: 10em;  
color: white;
display: inline-block;
float:left;
width: 150px;
height: 35px;
line-height: 35px;
text-align: center; 
border-right: 1px solid #bbb;
border-top: 1px solid #bbb;
background-color: green;
/*padding: 14px 16px;*/
}

#menu li ul li{
padding: 7px 32px;
width: auto;
height: auto;

}
#menu li:last-child {
    border-right: none;
}

#menu ul ul {
flex-direction: column;
padding: 0;
}

#menu li li {
background-color: orange;
}

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

Updating the DOM using jQuery after receiving an AJAX response

I'm grappling with the most effective way to modify the DOM after receiving an AJAX response. I prefer to showcase the code rather than attempt to articulate my dilemma. // page contains several checkboxes $("input[type='checkbox']").live(& ...

Looking for a way to retrieve JSON data from an HTML page using JavaScript? Look no further

There is a page that sends me JSON data. You can make the request using the GET method: or using the POST method: argument --> unique_id=56d7fa82eddce6.56824464 I am attempting to retrieve this information within my mobile application created with I ...

The Jquery ajax function is functional on a local environment, but fails to work when

Can someone please help me with this issue? I've been trying all day to figure it out, but I can't seem to... So, I have this function: function doSearch(){ $('#dg').datagrid('load',{ search: $('#sea ...

PyQt TreeView scrollbar obstructing the header

I've been experimenting with the QTreeView widget (instead of QListView) in order to have a horizontal header. Additionally, I wanted to use stylesheets to customize the colors and appearance of the header and scrollbars. However, there is an issue w ...

Encountering an Unexpected Token Error While Parsing JSON with jQuery

Utilizing the Envato API with jQuery to collect user stats is my current project. An example JSON response that I will display is as follows: { "new-files-from-user":[ { "thumbnail":"http://3.s3.envato.com/files/60560.jpg", "tags":"", "use ...

Ways to alert user prior to exiting page without initiating a redirect

I have a feature on my website where users can create and edit posts. I want to notify them before leaving the page in these sections. Here's how I can accomplish that: //Add warning only if user is on a New or Edit page if(window.location.href.index ...

What is the best way to send progress updates from PHP to the webpage following a user's button press?

As a user clicks on a series of buttons on the page, it triggers a PHP script through jQuery utilizing the .ajax() method. Currently, I am appending a concatenated string dump of "progress updates" to a status placeholder DIV using the success: function(da ...

Unable to retrieve the desired dropdown element using xpath location strategy

On my website, I have a drop-down menu for selecting time zones and I need to be able to access the options easily. https://i.sstatic.net/jR4gx.png Here is the HTML code snippet: <li> <div id="ember2503" class= ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...

Adjust the width of a float-right container to its maximum width

Looking for a solution similar to the one discussed in this question: CSS - Float to max width In my project, I am working on a layout that involves a <pic> / <info> style setup, with a twist - I want it to be responsive when the user resizes ...

Organizing and Analyzing data in a ng-repeat with AngularJS, influenced by a higher level ng-repeat

Currently tackling the challenge of creating a fairly intricate ng-repeat that involves filtering and parsing. My initial step is to employ ng-repeat to populate a table with 12 months starting from the current month. Following that, I am organizing two ...

Unable to retrieve the value of a clicked button using jQuery

i am attempting to extract an array from checked buttons when a button is clicked. Although I can successfully retrieve the array, I am struggling to obtain the value of the clicked button. the code snippet below illustrates my attempt: $('.multiple& ...

Challenges with uploading files using jQuery

Click here to upload a file I'm trying to create a feature where users can choose an image and have it displayed in place of the "trees" image. Feeling stuck, I could really use some guidance. Check out the code below: <div class="user-editab ...

Is there a way to add text to a table row using knockout?

I have been tasked with incorporating knockout js into my application. The table structure is as follows: <table> <tr> <th> Name </th> <th> Category </th> ...

Tips on emphasizing all div elements and incorporating navigation to each of them

I am seeking a method to enhance a div with highlighting when there is a click or mouseover event. For instance, changing or adding a border color using JavaScript on click or mouseover is straightforward. Recently, I have been contemplating the idea of a ...

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

What method can be used to obtain a parallel vector on a plane that has been struck by an intersecting ray?

Issue at hand: https://i.sstatic.net/H5g5M.jpg Given parameters: intersect, n, p. With p representing a random point in the space, and N as the normal of the plane. Desired result: w Approach attempted in my shader code: "vec3 n = normalize(faceNormal ...

Using HelloJS and AngularJS for an asynchronous call to the login function with oAuth

I've been working on integrating HelloJS into my AngularJS app. According to the documentation, in order to authenticate I need to call the login function like this: hello("google").login().then(function(){ }); After that, I should listen for the &a ...

Effectively encoding and decoding AJAX and JSON objects with PHP scripting

I've successfully set up a basic HTML file with a fixed JSON object. My goal is to transfer this object to a PHP file named text.php, encode it, decode it, display it in the PHP file, and then showcase it back in the HTML file. <!DOCTYPE html> ...

Improving search functionality with autocomplete in EasyAdmin 3.3 filter options

Is there a quick solution in easyadmin 3.3 to implement an autocomplete feature for filters? I have successfully used it in forms, but encountering an undefined error with filters. public function configureFields(string $pageName): iterable { r ...