What could be causing the error message to appear when I click on my dropdown button?

I am encountering an issue with my dropdown menu activation. The error message I receive is:

Uncaught Reference Error : DropDown not defined

This problem started when the dropdown was in its own div within the header, and now persists even after moving it into a nav list.

function  DropDown() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick  =   function(event) {  
  if  (!event.target.matches('.dropbtn'))  {    
    var  dropdowns = document.getElementsByClassName("dropdown-content");    
    var  i;    
    for  (i =  0; i < dropdowns.length; i++) {      
      var  openDropdown = dropdowns[i];      
      if  (openDropdown.classList.contains('show'))  {       
        openDropdown.classList.remove('show');     
      }    
    } 
  }
}
body {
  margin: 0px;
}

#logo {
  width: 130px;
  float: left;
  padding-top: 13px;
  padding-bottom: 13px;
}

.container {
  width: 80%;
  margin: 0;
  float: left;
  padding: 0;
}

header {
  background-color: #55d6aa;
  padding: 0;
  margin: 0;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

nav {
  float: right;
  font-size: 14px;
  margin: 0;
}

nav ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

nav li {
  display: inline-block;
  margin: 0;
  padding-top: 23px;
  margin-left: 10px;
  position: relative;
}

nav a {
  color: black;
  text-decoration: none;
  text-transform: uppercase;
}

nav a:hover {
  color: darkblue;
}

nav a::before {
  content: '';
  display: block;
  height: 5px;
  width: 100%;
  background-color: black;
  top: 0;
  width: 0%;
  position: absolute;
  transition: all ease-in-out 250ms;
  border-radius: 10px 10px 10px 10px;
}

nav a:hover::before {
  width: 100%;
}

nav a:focus {
  background-color: #55d6aa;
}

#banner {
  width: 100%;
  height: 114px;
  margin: 0;
  padding: 0;
}

#barline {
  height: 30px;
  width: 100%;
  background-color: #55d6aa;
  margin: 0;
  padding: 0;
  float: right;
}

.dropbtn {
  background-color: #55d6aa;
  margin: 0;
  border: 0;
  color: black;
  text-decoration: none;
  text-transform: uppercase;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 60px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Page title</title>
  <link rel="stylesheet" href="CSS/Style.css">
  <script type="javascript" src="Java/Java.js"></script>
</head>

<header>




  <div class="container">

    <img id="logo" src="IMG/Logo.png" alt="logo"></img>


    <nav>

      <ul>

        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Team</a></li>
        <li><a href="#">Contact</a></li>
        <li><a onclick="DropDown" class="dropbtn">MORE</a>
          <div id="myDropdown" class="dropdown-content">
            <a href="">Profile</a>
            <a href="">Settings</a>
            <a href="">Log Out</a>

          </div>
          </a>
        </li>

      </ul>

    </nav>

  </div>

</header>

<body>

  <div>

    <img id="banner" src="IMG/MountainBanner.jpg" alt="Mountains"></img>


  </div>

  <div id="barline">

  </div>





</body>

</html>

Answer №1

If you want your webpage to load faster, consider moving your <script/> tag to the bottom of the HTML code. Additionally, make sure to place your header tag within the body tag for proper structure.

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Page title</title>
  <link rel="stylesheet" href="CSS/Style.css">
  
</head>
<body>
  <header>
   . . .
  </header>
  <div>
    <img id="banner" src="IMG/MountainBanner.jpg" alt="Mountains"></img>
  </div>

  <script type="javascript" src="Java/Java.js"></script>
</body>
</html>

Answer №2

Oops! There seems to be a syntax issue.

It looks like the onclick="DropDown()" was missing a set of parentheses.

Furthermore, you might want to consider moving the <body> tag after the </head> tag for better structure, although this won't affect your script.

Lastly, remember that JAVA is not JavaScript, so it's recommended to rename the js file and folder accordingly.

Here's a cleaner version with suggested eventListeners:

window.addEventListener("load", function() {
  const dd = document.getElementById("myDropdown");
  document.querySelector(".dropbtn").addEventListener("click", function(e) {
    dd.classList.toggle("show");
  })
})
window.addEventListener("click", function(event) {
  if (!event.target.matches(".dropbtn")) {
    [...document.querySelectorAll(".dropdown-content.show")]
    .forEach(elem => elem.classList.remove("show"));
  }
});
/* CSS styles */
body {
  margin: 0px;
}
/* Add more CSS styles as needed */

<!doctype html>
<html lang="en">

<head>
  <title>Page title</title>
  <link rel="stylesheet" href="CSS/Style.css">
  <script type="javascript" src="Java/Java.js"></script>
</head>

<body>
  /* Your HTML content here */
</body>

</html>

Answer №3

When you engage with the drop-down button, the DropDown Function is triggered but if you have not defined the function----here's a solution:

<li><a onclick={DropDown} class="dropbtn">MORE</a>
                <div id="myDropdown" class="dropdown-content">

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

What could be the reason for my jQuery script not functioning properly?

<script> var currentLevel = 0; $(document).ready(function(){ $("#tolevel_" + (currentLevel+1) ).click(function(){ $("#level_" + currentLevel).hide(500,'swing', function(){ $("#level ...

My NodeJS MongoDB application is being bombarded by an infinite loop of "Sending request..." messages from the Postman

This is the complete code for my chatbot application const express = require('express'); const app = express(); const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const bodyParser = require(& ...

How to handle and display validation errors in an AJAX post request using express-validator in Node.js/Express

I am in the learning phase with Node and attempting to display validation errors (using express-validator and express 4) when a user submits a form. The validator appears to be functioning properly because when I log the data to the console, everything lo ...

Discovering package utilities with npm commands

When integrating a package into my code, such as: import { Text, View, StyleSheet } from "react-native"; How can I discover the full range of utility functions like Text, View, etc. that are available in the react-native package? Is there an n ...

Developing tests for an asynchronous function

I recently encountered a bug in my AWS Lambda code written in NodeJS 6.10 that caused me two sleepless nights. I didn't conduct integration testing, relying solely on unit tests, which led to the oversight. After inserting return workerCallback(err);, ...

Nested Angular click events triggering within each other

In my page layout, I have set up the following configuration. https://i.stack.imgur.com/t7Mx4.png When I select the main box of a division, it becomes highlighted, and the related department and teams are updated in the tabs on the right. However, I also ...

After a page refresh, the Vuex state ends up being null within the mutation rather than the expected predefined

When developing a basic application, I set up a series of mutations and actions linked to the component creation hook. However, upon refreshing the browser using F5 and accessing vue-devtools on the Vuex tab, an unexpected error occurs at the beginning of ...

Examining the order in which tabs are navigated

Ensuring correct tab keyboard navigation order within a form is crucial for one of our tests. Query: How can the tab navigation order be verified using protractor? Our current method involves repeating the following steps for each input field in a form ( ...

Update the hidden input's value by the ZIP code entered

I'm currently working on setting up arrays for specific regions and then comparing them to the zip code entered in order to designate the value of a hidden field (which signifies the region). No matter what I input, it always seems to result in "Not F ...

Vanish Dropdown upon clicking Using JavaScript

Hey, I'm new to web development and I'm currently working on creating a web app for iPhone. Everything is going smoothly except for one issue - my dropdown menu works perfectly on desktop Chrome, but on the iPhone's Safari browser, I can&ap ...

Display the next page once two distinct service requests have been received

When I need to display a page after retrieving data from two different services, service1 and service2, how can I achieve this without nesting the second service call inside the first one? Instead of chaining the service calls, I want to make separate req ...

Insert a new row in a table using jQuery

Could you help me figure out how to move an element within a table row into another table using jQuery? I've been considering using 'append', but it requires session handling. What is the best method in this case: should I use ajax, JSON, PH ...

What is the most effective way to organize a collection according to the specific order specified in another array?

I have an array of objects, with each element containing another nested object like this: data = [ { name: "A", type: "AA", children: [ { id: 1, name: "Child-A", admin: ["Y"] }], other: "NA" }, { name: "B", type: "BB", ch ...

Creating a variable in JavaScript using Smarty in Prestashop 1.6

I am currently facing an issue with defining a JavaScript variable that fetches its value from a Smarty variable. In my PHP controller, here is what I have implemented: public function hookDisplayBackOfficeHeader() { $this->context->controller-&g ...

What is the best way to apply one JavaScript code to two separate HTML elements?

I am currently experiencing an issue where only the first mp4 file is working properly, while the second one does not. I am considering removing the stylesheet part as it is proving to be difficult for me to handle. I lack the skills to implement other sol ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

What are some strategies to optimize debugging and troubleshoot errors in a Node.js http post request?

This particular example may seem a bit lacking in context, I admit. Nonetheless, when attempting this request, the following error surfaces: TypeError: Invalid data, chunk must be a string or buffer, not object My suspicion is that the issue lies within ...

Tips for styling Ajax.ActionLink elements with CSS

Hi there, I'm trying to style a navigation bar using CSS. I'm pulling the navigation bar values from a database using Ajax.ActionLink. I attempted to use JavaScript but encountered an error stating "jQuery is not defined", Here's the cod ...

Trigger Popup Automatically When Anchor Exists

I have created an image gallery that loads images using Ajax when the page first loads and includes a "Load More" button. You can view a working example here (Plunker) My current challenge is automatically loading and opening a popup of an image if its ID ...

Protractor is displaying an error message of "unable to locate element testability" when attempting to access an element

I'm encountering an issue with Protractor while trying to access a variable that stores the return value of "elements.all". As someone who is new to Protractor, I wasn't sure how to select elements by a custom attribute. Thankfully, I received so ...