Troubleshooting Problem with CSS and Javascript Dropdown Menu

Greetings, fellow web designers! I am relatively new to the world of web design and currently, I am immersed in the process of creating a website. My current project involves implementing a dropdown menu using CSS and Javascript. While I have made significant progress in getting everything to work smoothly, I am facing one final hurdle to overcome. The issue at hand is that the dropdown menu content is appearing to the left of the container rather than below the relevant parent menu option.

Take a look at the screenshot

function myFunction1() {
  // Your Javascript functions here
}
.navbar {
  /* Your CSS styles here */
}
<div class="navbar">
  <button class="btn1" value="About Us"> About Us </button>
  <div class="dropdown">
    <button class="dropbtn1" onclick="myFunction1()"> Rehearsals </button>
    <div class="dropdown-content1">
      <a href="#">> Live Room </a>
      <a href="#">> Isolation Room </a>
    </div>
  </div>
  // Additional menu items and content can go here
</div>

Answer №1

It seems like there is some unnecessary code and repetition in your post that could be streamlined. Ensuring proper HTML structure, class names, and IDs will not only reduce redundancy but also improve the semantics of your code.

Menus are essentially just a list of choices, so using the <ul> element with <li> elements nested inside is the recommended approach. Through CSS styling, you can easily transform the menu from a vertical to a horizontal layout, which is a common practice.

When assigning classes and IDs, make sure to give unique IDs to elements that require individual attention and use classes for styling elements within a group. This practice simplifies styling and eliminates the need for duplicative code.

Regarding JavaScript, it's best to avoid inline HTML event attributes (onclick, onmouseover, etc.). You can refer to this post for more information on why this outdated method is not recommended for setting up event handlers.

Below is a revised version of your menu code, where you can observe the reduction in code complexity and improved clarity.

// To access and manipulate elements:
var dd = document.querySelectorAll(".db");

// Setting up click and mouseout events for drop-down menus
for(var i = 0; i < dd.length; i++){
  dd[i].addEventListener("click", function(evt){ toggleElement(evt.target); });
  dd[i].addEventListener("mouseout", function(evt){ hideElement(evt.target); });  
}

// Function to toggle menu visibility
function toggleElement(element) {
  element.querySelector("ul").classList.toggle("hide");
}

function hideElement(element) {
  var el = element.querySelector("ul");
  
  if(el){
    el.classList.add("hide");
  }
}
.navbar {
  font-family: Impact, Haettenschweiler, Franklin Gothic Bold, Arial Black, sans-serif;
  margin: 0;
  padding: 0;
  list-style: none;
}

li { 
  text-align: center;
  color: white;
  margin: 0;
  padding: 0;
}

/* More CSS styling goes here */
<ul class="navbar">
  <li id="dropbtn1" class="db"><a href="...">About Us</a></li>

  <!-- More menu items go here -->

  <li id="dropbtn6" class="db"><a href="...">Contact Us</a></li>
</ul>

Answer №2

To properly display dropdown items, it's important to assign a relative position to the list items with the class name dropdown.

Although this isn't a modification of your own code, the following CSS snippet showcases the correct relationship between parent and child elements for dropdown menus:

.dropdown-container {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-left: -100px;
}

Here's a relevant JSFiddle for reference

Answer №3

When the CSS class dropdown has its width set to 100%, all .dropdown-content1 elements within that parent will have the same width and alignment. This is why the drop down menu appears to move to the left.

To fix this, modify the .dropdown class as follows:

.dropdown {
    float: left;
}

You may notice that your buttons may appear distorted initially. This is because the inner CSS classes dropbtn1, dropbtn2, etc. have their widths set to 16.667%. Changing these widths to 100% will make the dropdown menu behave as expected.

Answer №4

To make the dropdown menu functional, you should adjust the width of the elements to match the parent class ".dropdown". Each dropdown-content class should occupy 100% of the parent width. The parent dropdown class needs to have a position of relative, while the child content classes should be positioned absolutely. Specify the positioning of the dropdown inside the parent (e.g., 50px below the parent).

Below is a revised version that should work for your setup...

UPDATE: The "About" and "Contact Us" href links in your HTML had errors due to missing quotes. I also simplified the Javascript and CSS for better organization. While it can still be improved further, I've combined several elements and classes to illustrate the concept for you to refine.

Javascript:

function myFunction(ele) {
  hideAll();
  ele.nextElementSibling.style.display="block";
}

function hideAll() {
  var dropdowns = document.getElementsByClassName("dropdown-content");
  for (var i = 0; i < dropdowns.length; i++) {
    dropdowns[i].style.display="none";
  }
}

window.onclick = function(event) {
      if (!event.target.matches('.dropbtn')) {
        hideAll();
    }
}

HTML:

<div class="navbar">
    <div class=dropdown>
      <button class="dropbtn btn1" value="About Us" onclick="window.location.href='https://uklivesound.000webhostapp.com/aboutus.html'">About Us</button>
    </div>

    <div class="dropdown">
      <button  class="dropbtn dropbtn1" onclick="myFunction(this)">Rehearsals</button>  
      <div class="dropdown-content" id="myDropdown1">
        <a href="https://uklivesound.000webhostapp.com/liveroom.html">Live Room</a>
        <a href="https://uklivesound.000webhostapp.com/isolationroom.html">Isolation Room</a>
      </div>
    </div>

    <div class="dropdown">
      <button class="dropbtn dropbtn2" onclick="myFunction(this)">Recording</button>
      <div class="dropdown-content" id="myDropdown2">
        <a href="https://uklivesound.000webhostapp.com/audiorecording.html">Audio</a>
        <a href="https://uklivesound.000webhostapp.com/videorecording.html">Video</a>
      </div>
    </div>

    <div class="dropdown">
      <button class="dropbtn dropbtn3" onclick="myFunction(this)">For Hire</button>  
      <div class="dropdown-content" id="myDropdown3">
        <a href="https://uklivesound.000webhostapp.com/hirepackages.html">Event Packages</a>
        <a href="https://uklivesound.000webhostapp.com/largeevents.html">Large Events</a>
        <a href="https://uklivesound.000webhostapp.com/equipmenthire.html">Equipment</a>
        <a href="https://uklivesound.000webhostapp.com/bandhire.html">Bands</a>
      </div>
    </div>

    <div class="dropdown">
      <button class="dropbtn dropbtn4" onclick="myFunction(this)">Other Services</button>  
      <div class="dropdown-content" id="myDropdown4">
        <a href="https://uklivesound.000webhostapp.com/buyandsell.html">Buy & Sell</a>
        <a href="https://uklivesound.000webhostapp.com/repairs.html">Repairs</a>
      </div>
    </div>

    <div class=dropdown>
      <button class="dropbtn btn2" value="Contact Us" onclick="window.location.href='https://uklivesound.000webhostapp.com/contact.html'">Contact Us</button>
    </div>
</div>

CSS:

.navbar {
     float:left;
     font-family:Impact, Haettenschweiler, Franklin Gothic Bold, Arial Black,sans-serif;
     height:auto;
     width:100%;
     display:inline-block;
     margin:0;
     padding:0;
     position:relative;
 }

 .navbar a {   font-size: 2em;     font-weight: 100;
     color: white;
     text-align: center; }

 .dropdown {
    position: relative;
    float:left;
    width:16%;
    }

 .dropdown-content {
     display: none;
     position: absolute;
     top: 50px;
     background-color: #f9f9f9;
     width:100%;
     box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
     z-index: 1;
     padding:0px;
     height:auto;
     }

 .dropdown-content a {
   text-decoration: none; text-align:center; height:auto;
   display: block; width:100%; padding:0px; background-color:#000000; border: 1px solid white;
   }

 .dropdown-content a:hover {
   color: black;
   padding: 12px 16px;
   text-decoration: none; text-align:center; height:auto;
   display: block; width:100%; background-color:#FFFFFF; border: 1px solid black;
   font-family:Impact, Haettenschweiler, Franklin Gothic Bold, Arial Black,sans-serif;
   transition-duration:0.5s; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2)
   }

 .dropbtn {
   color: white;
   padding:0px;  margin:0px;
   font-size:2em;
   border: 1px solid white;
   cursor:pointer; width:100%; float:left;
   }

 .dropbtn:hover, .dropbtn:focus {
   background-color:#FFFFFF;
   color: black;
   border: 1px solid black;
   font-family:Impact;
   transition-duration:0.5s;
   box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
 }

 .btn1 {
    background-color:#71aace;
  }

 .btn2 {
    background-color:#D84E92;
  }

 .dropbtn1 {
     background-color:#6c73b1;
   }

 .dropbtn2 {
     background-color:#d3c530;
   }

 .dropbtn3 {
     background-color:#82c845;
   }

 .dropbtn4 {
     background-color:#8f65a1;
   }

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

Unable to achieve horizontal alignment with DIV element set as inline-block

Currently, I have five columns that are aligned using the display:inline-block. Everything seems to be working fine, but there's a peculiar issue that arises when I refresh the page multiple times. Occasionally, while the first column remains at the t ...

Unable to change the NodeJS version

Nodejs installation not updating Nodejs version $ nodejs --version v8.10.0 $ sudo npm install -g nodejs@latest + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c6c7cccdc2dbe89886988698">[email protected]</a> up ...

Can an excess of CSS impact the speed and performance of a website?

After conducting thorough research on this specific topic, I was unable to locate the precise answer that I require. For instance, there are numerous divs within my project that necessitate a border. One approach is to create a distinct CSS class such as ...

Unable to display background image and color on Internet Explorer

The background beneath the slider and footer appears normal in most browsers, but there seems to be an issue with Internet Explorer. Check it out at this link: Do you have any suggestions on how to fix this? ...

Challenges with organizing content using spans in Bootstrap 3

Looking for some help with TB3 here. I've created a jsFiddle to showcase my attempt at building a small minitron, which is essentially a mini jumbotron. https://i.sstatic.net/VxruB.png The idea is to have each 'minitron' contained within a ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

The callback function for the XMLHttpRequest object is not triggered when making a cross-domain request using jQuery/Ajax

Looking for some help with this code snippet I have: $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentCo ...

Utilize AJAX to dynamically insert data into the database

I have created a JSP page that displays records, and now I am looking to include a dynamic link or button in the JSP that allows inserting data into the database without needing to refresh the page. This link should open a pop-up window with input fields ...

What is the best way to determine which CSS class is shown when the page is loaded using JQuery?

I am facing a dilemma with displaying my site logo. I have both an image version and a text version, and I want to choose which one to display based on the vertical position on the page and the screen width. <a class="navbar-brand" id="top-logo" href=" ...

Preventing the addition of hash tags to the URL by the anything slider

Why does the Anything Slider add hash tags like #&panel1-1 to the end of the URL? I attempted using hashtags:false but it was unsuccessful. Are there alternative methods to prevent it from creating these hashtags? ...

Creating an arrow icon alongside a pseudo:hover::before element

This is my custom code snippet: .privacycheck1 { position: relative; top: 265px; background-color: #CF0000; width: 24px; height: 24px; left: 843px; border-radius: 50px; border: 5px #E60000; } .privacycheck1::before { position: relative ...

How to Customize the Drawer Color in Material-UI v5

I'm currently using MUI v5 in my project and I am encountering some challenges while attempting to style a Drawer component with a black background color. As this update is relatively new, I have not been able to find much information on customizing t ...

Extracting text from HTML elements using BeautifulSoup

I'm working with the following html code and I want to extract the text that comes after <b>Name in Thai</b>, specifically : this is what I want content = """ <html><body><b>Name of Bangkok Bus station:</b> <spa ...

Buttons in the Bootstrap navbar dropdown menu do not display when the navbar is collapsed into a hamburger icon

My bootstrap navbar has a CSS media query that collapses it and allows it to be opened via a hamburger button when the screen size is below a certain threshold (for mobile devices). However, I have encountered an issue with a dropdown menu within the navba ...

JavaScript Function for Finding the Time Difference Between Two Dates (in Years, Days, Hours, or Less than One Hour)

I need to calculate the time difference between 2 dates and display it. If the difference is greater than a year, show the number of years only. If it's more than a day, show the number of days. If it's less than a day, show the number of hours. ...

In HTML, specify that the height of both the `html` and

I am facing an issue with the container-about div. I have set its height to 100% so that the div occupies the entire width and height after the header div. The problem is that currently, I cannot scroll to view the full text. It would be great if there wa ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

The JS copy function is successful when operating on a single element, but it encounters issues when attempting to run on multiple elements, only copying

My code includes a copy function that copies the data from a textarea to the clipboard when a button is clicked. The functionality works perfectly for the first textarea, but for subsequent textareas, the buttons do not perform the copy action. Check out ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Promises and Their Valuable Variables

Recently I began learning JavaScript and I'm encountering some confusion. Here's the code snippet that is causing me trouble: api.posts .browse({ limit: 5, include: 'tags,authors' }) .then(posts => { posts.forEach(post =&g ...