Dropdown menu will appear when you click on one of the menu items

Can someone help me create a dropdown menu using a JavaScript function that toggles on click? I've attempted to do so with the following code, but it's not working as expected. Could you please point out where I might be going wrong? I'm looking to implement this purely in JavaScript and I am utilizing SASS for styling purposes.

Below is the code snippet:

let home = document.getElementById('home');
let underhome = document.querySelector('under-home');

home.addEventListener('click', function() {
  underhome.classList.toggle('open');
});
.navbar .slider .hammburger-links {
  padding: 0 1.250em;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.navbar .slider .hammburger-links a {
  padding: 0 1.500em;
  text-decoration: none;
  font-family: "Helvetica", Arial;
  font-size: 11px;
  color: #a6adb4;
}

.navbar .slider .hammburger-links .under-home {
  position: absolute;
  top: 5%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  background: #F6F8F9;
  min-width: 12.5em;
  min-height: 12.5em;
  z-index: 1;
  display: none;
}

.navbar .slider .hammburger-links .under-home a {
  margin: 10px 0;
}

.navbar .slider .hammburger-links .open {
  display: inline;
<div class="navbar">
  <div class="slider">
    <div class="hammburger-links">
      <a href="" id="home">HOME</a>
      <div class="under-home">
        <a href="">WORLD NEWS</a>
        <a href="">TRAVEL</a>
        <a href="">TECHNOLOGY</a>
        <a href="">CITY</a>
        <a href="">CULTURE</a>
        <a href="">MORE...</a>
      </div>
      <a href="">DISCOVERY</a>
      <a href="">PHOTOS</a>
      <a href="">CONTACT</a>
      <img src="images/navbar-img.png" alt="">
    </div>
  </div>
</div>

Answer №1

Several modifications have been made - the key changes are described below:

  • To begin with, the navbar wrapper was added which was missing in your code snippet and the .querySelector('under-home') was corrected by adding the . (class selector),

  • position: relative was added to .hammburger-links to ensure that the sub-menu is positioned relative to this element,

  • e.preventDefault() was included in your eventListener to disable the default action of clicking a hyperlink (we need the menu toggle functionality here),

  • For .open, replaced display: inline with display: flex,

Check out the demo below:

let home = document.getElementById('home');
let underhome = document.querySelector('.under-home');

home.addEventListener('click', function(e) {
  e.preventDefault(); /* prevent default hyperlink action */
  underhome.classList.toggle('open');
});
.navbar .slider .hammburger-links {
  padding: 0 1.250em;
  display: flex;
  align-items: center;
  position: relative; /* added */
}

.navbar .slider .hammburger-links a {
  padding: 0 1.500em;
  text-decoration: none;
  font-family: "Helvetica", Arial;
  font-size: 11px;
  color: #a6adb4;
}

.navbar .slider .hammburger-links .under-home {
  position: absolute;
  top: 1.5em; /* adjusted */
  display: flex;
  flex-direction: column;
  background: #F6F8F9;
  min-width: 12.5em;
  min-height: 12.5em;
  z-index: 1;
  display: none;
}

.navbar .slider .hammburger-links .under-home a {
  margin: 10px 0;
}

.navbar .slider .hammburger-links .open {
  display: flex; /* changed */
}
<div class="navbar">
  <div class="slider">
    <div class="hammburger-links">
      <a href="" id="home">HOME</a>
      <div class="under-home">
        <a href="">WORLD NEWS</a>
        <a href="">TRAVEL</a>
        <a href="">TECHNOLOGY</a>
        <a href="">CITY</a>
        <a href="">CULTURE</a>
        <a href="">MORE...</a>
      </div>
      <a href="">DISCOVERY</a>
      <a href="">PHOTOS</a>
      <a href="">CONTACT</a>
      <img src="https://via.placeholder.it/200" alt="">
    </div>
  </div>
</div>

Answer №2

Give this a try

let homepage = document.getElementById('home');

homepage.addEventListener('click', function() {
 var element =  document.getElementById('under_home');
   element.classList.toggle("open");

});
.navbar .slider .hammburger-links {
  padding: 0 1.250em;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.navbar .slider .hammburger-links a {
  padding: 0 1.500em;
  text-decoration: none;
  font-family: "Helvetica", Arial;
  font-size: 11px;
  color: #a6adb4;
}

.navbar .slider .hammburger-links .under-home {
  position: absolute;
  top: 14%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  background: #F6F8F9;
  min-width: 12.5em;
  min-height: 12.5em;
  z-index: 1;
  display: none;
}

.navbar .slider .hammburger-links .under-home a {
  margin: 10px 0;
}

.navbar .slider .hammburger-links .open {
  display: inline;
  }
<div class="navbar">
<div class="slider">
            <div class="hammburger-links">
                <a href="" id="home">HOME</a>
                <div class="under-home" id="under_home">
                    <a href="">WORLD NEWS</a>
                    <a href="">TRAVEL</a>
                    <a href="">TECHNOLOGY</a>
                    <a href="">CITY</a>
                    <a href="">CULTURE</a>
                    <a href="">MORE...</a>
                </div>
                <a href="">DISCOVERY</a>
                <a href="">PHOTOS</a>
                <a href="">CONTACT</a>
                <img src="images/navbar-img.png" alt="">
            </div>
        </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

Tips for generating automatic views in Backbone without manual instantiation

Is there a more efficient way to instantiate the view rather than directly below the definition? var BVApp = Backbone.View.extend({ Name: 'BVApp', // do chonka stuff }); $A.Class.add(new BVApp()); ...

Stop unauthorized entry into JavaScript files

Is there a method to secure JavaScript files from unauthorized access? <script src="JS/MyScript.js" type="text/javascript"> It is crucial that users are unable to access the MyScript.js file. I am seeking advice on how to achieve this. Is it even ...

Once the form is submitted, Vue automatically resets all the data

export default { data() { return { usrName: null, pass1: null, pass2: null, regState: {stateCode:-1}, } }, methods: { register: function () { this.axios.post("/login/", { baseURL: 'http://127 ...

Utilize jQuery to seamlessly transfer each recorded audio file from rows to corresponding input fields within the table

I have a table below with 2 rows but it can be doubled with a button (Add another Word media) and only one submit button for all rows: <tbody> <tr class="form-row dynamic-medias" id="medias-0"> <td class=&quo ...

margin around the masterpage

Currently, I am utilizing a master page in ASP.NET (using Visual Studio Express 2015) and overall everything is functioning properly. However, there seems to be an unsightly space around the edges when viewing it in a browser. While not a critical issue, ...

What is the method to retrieve a checkbox value within a datatable when employing pagination?

I recently came across an issue with my datatable where I had implemented a checkbox in the first column of each row. However, when I attempted to check the checkbox using an AJAX call, it only worked for the first page and not for any subsequent pages. H ...

The footer is refusing to show up at the bottom of the page

Why is my footer floating in the middle of the page? It's driving me crazy. I really hope it's a quick fix. I've searched online and all the solutions point to having a fixed footer, but I don't want that because it looks bad on smaller ...

Can you please provide a method for determining which characters are adjacent to each other

I am in the process of developing a markdown editor and I require a check to identify if adjacent characters are specific characters, removing them if they match or adding them otherwise. For example, if the selected text is surrounded by two asterisks li ...

What could be the reason for the electron defaultPath failing to open the specified directory?

Hi, I'm experiencing difficulties opening the directory path (/home/userxyz/Releases/alpha) using electron. This is what I have attempted: I have a similar path on Ubuntu: /home/userxyz/Releases/alpha When trying to access this path with the fo ...

The form submits immediately after jquery is activated

One challenge I'm facing involves multiple forms on a single page being submitted using jQuery. Currently, I have the following code snippet: $("form").submit(function (e) { // Submit form via Ajax }); The problem arises when the form is only s ...

Tips for stretching the background image to full width

I am trying to set the background to be full width like the image below (must be responsive). However, when I applied it, the result looks like this and crops the bottom part. Can someone please assist me with this issue? ...

Comparing partial strings using Mongodb aggregation techniques

After populating my MongoDB database with around 5000 questions, I am now looking to group questions together that are partially similar, ranging from 70% to 80% similarity, and then send them to the frontend. I attempted to achieve this using the pipelin ...

Experiencing difficulties positioning svg text path in the center using CSS on desktop devices

I've looked into other SVG text questions, but I'm struggling to understand my mistake. Currently, I'm working on a live site at and implementing the following code: <svg class="svg-width desktop" style="margin:auto"> <path ...

Seeking a template for a server-side programmer who lacks proficiency in CSS and design?

Hey there all you wise folks! So here's the deal - I'm a PHP/JavaScript wizard when it comes to logic and server-side stuff, but I really suck at design, CSS, and all things arty. Does anyone have any recommendations for a template or tool that ...

Selenium can locate an element by its CSS selector that comes after a specific element

How can I locate the text "Interesting" which is the first occurrence of the class b after h1.important when using Selenium? <div class="a"> <div class="b">Not interesting</div> </div> <div class="title"> <h1 c ...

Transforming the appearance of an Imagebutton upon clicking with the power of Javascript

I am attempting to update the image URL when a specific image button is clicked, however, I am encountering an issue where the image does not change. It seems that none of the JavaScript functions are successfully altering the image and are unable to iden ...

Utilizing the Bootstrap 5 Alpha validation script within a React environment

I've been working on implementing Bootstrap 5 alpha's validation in my React app. The form should not submit if left blank, and it should display a check or an error mark at the bottom accordingly. So far, I've added the necessary node pac ...

Is there a way to manipulate text in JQuery without altering the inner element?

I am struggling with an issue in my HTML code. Currently, I have the following structure: <h3 id="price">0.00<sup id="category">N/A</sup></h3> My intention is to use AJAX to replace the content within the <h3 ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...

Crafting an innovative horizontal CSS spotlight using conic-gradient styling

Seeking advice: I need to implement three spotlights on a webpage One shining directly downwards One angled from the left to the upper-top One angled from the right to the upper-top I managed to create a vertical spotlight using CSS conic-gradient, but I ...