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

Why isn't the right-clear property functioning correctly?

My understanding of `clear: left`, `clear: right`, and `clear: both` in CSS has always been a bit fuzzy. I know that `clear: both` means it prevents floating elements from appearing on both sides, but I recently did some testing here. I expected the layout ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

Handlebars does not support loading data into variables using Express

My NodeJS/Express application utilizes Handlebars for templates, and everything works smoothly except when attempting to display data retrieved from an Express API. The data is successfully fetched and can be viewed in the Chrome debugger. In the problem ...

Visual Studio Terminal displaying "Module Not Found" error message

After successfully downloading nodejs onto my computer, I created a javascript file and stored it in a folder on my desktop. However, when I tried to run the JS code using the Visual Studio terminal, I encountered the following error message. I am confiden ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

Compiling TypeScript into JavaScript with AngularJS 2.0

Exploring the capabilities of AngularJS 2.0 in my own version of Reddit, I've put together a script called app.ts ///<reference path="typings/angular2/angular2.d.ts" /> import { Component, View, bootstrap, } from "angular2/angular2 ...

Display the iframe website without it being visible to the user

Is there a way to load a separate website, such as a Wikipedia article, in an iframe on a webpage without freezing up the whole page when it becomes visible after clicking a "show" button? And if not, how can we display a loading gif while the iframe is ...

Exploring the movement from one component to another in React Native

When working with React Native, I encountered a challenge in navigating between two views. The issue arises from having the button to navigate on one component while my main component is elsewhere. I am using react-navigation for this purpose. Here's ...

Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties. if ($scope.filters.filter1) $scope.filteredEntries = $scope.filteredEntries.filter(function (o) { return o.field1 === $scope.filt ...

Include a stylesheet as a prop when rendering a functional component

Using Next.js, React, Styled JSX, and Postcss, I encountered an issue while trying to style an imported component for a specific page. Since the stylesheets are generated for a specific component at render time, I attempted to include custom styles for the ...

What sets asyncData apart from methods in Nuxt.js?

I am currently utilizing asyncData to fetch data from an API, however it is restricted to pages and cannot be used in components. On the other hand, methods can be used in both pages and components. As these two methods function similarly, I am consider ...

What methods can I use to prevent an image from moving and trigger a specific action with the press of a key?

I'm currently teaching myself web programming and also working on improving my C++ skills. However, I am facing a challenge with Javascript. My main question is regarding how to create an "if statement" based on the location of an image. I am in the ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

Is there a way to make all DIVs in the same class have the same height as the tallest div?

I have 3 identical divs with an auto height value. How can I set the height of all divs in the same class to be equal to the highest div's height? Same Class Div Thank you in advance. ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

The CSS effect fails to take effect following an AJAX response

After a successful ajax response, I am attempting to apply a jQuery .css effect. However, it seems that this process is not working as expected because I am trying to retrieve the height of a newly created element and then applying it to another newly crea ...

Identify all anchor elements that contain image elements

I am on the hunt. I am looking for a CSS-Selector, but if that's not an option, a jQuery selector would work too. ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => vo ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...