JS on-click function is not functioning

Here is the HTML code I have for my navigation menu:

<nav role="navigation" class="nav">
    <ul class="nav-items">
        <li class="nav-item">
            <a href="#" class="nav-link"><span>About Us</span></a>
        </li> 
        <li class="nav-item dropdown">
            <a href="#" class="nav-link"><span>Divisions</span></a>
        <nav class="submenu">
            <ul class="submenu-items">
                <li class="submenu-item"><a href="#" class="submenu-link">Div 1</a></li>
                <li class="submenu-item"><a href="#" class="submenu-link">Div 2</a></li>
            </ul>
        </nav>
    </ul>
</nav>

This is my JavaScript code:

$(document).ready(function() {
    [].slice.call(document.querySelectorAll('.dropdown .nav-link'))
        .forEach(function(el) {
            el.addEventListener('click', onClick, false);
        });


    function onClick(e){
        e.preventDefault();
        var el = this.parentNode;
        el.classList.contains('show-submenu') ? hideSubMenu(el) : showSubMenu(el);
    }

    function showSubMenu(el){
        el.classList.add('show-submenu');
        document.addEventListener('click', function onDocClick(e){
            e.preventDefault();
            if(el.contains(e.target)){
                return;
            }
            document.removeEventListener('click', onDocClick);
            hideSubMenu(el);
        });
    }

    function hideSubMenu(el){
        el.classList.remove('show-submenu');
    }
});

I am facing an issue where the on-click action is not working. Can someone please provide some guidance? I found this code in an online tutorial and I am new to JavaScript. Any corrections or suggestions would be greatly appreciated. Thank you!

Answer №1

It seems like your code is functioning correctly, but there may be an issue with the CSS class causing the problem. Please double-check the CSS class you are using.

CSS:

.show-submenu > nav{
   display:block;
}
.submenu{
  display:none;
}

$(document).ready(function() {
  [].slice.call(document.querySelectorAll('.dropdown .nav-link')).forEach(function(el) {
    el.addEventListener('click', onClick, false);
  });


  function onClick(e) {
    e.preventDefault();
    var el = this.parentNode;
    el.classList.contains('show-submenu') ? hideSubMenu(el) : showSubMenu(el);
  }

  function showSubMenu(el) {
    el.classList.add('show-submenu');
    document.addEventListener('click', function onDocClick(e) {
      e.preventDefault();
      if (el.contains(e.target)) {
        return;
      }
      document.removeEventListener('click', onDocClick);
      hideSubMenu(el);
    });
  }

  function hideSubMenu(el) {
    el.classList.remove('show-submenu');
  }
});
.show-submenu > nav {
  display: block;
}

.submenu {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav role="navigation" class="nav">
  <ul class="nav-items">
    <li class="nav-item">
      <a href="#" class="nav-link"><span>About Us</span></a></li>
    <li class="nav-item dropdown">
      <a href="#" class="nav-link"><span>Divisions</span></a>
      <nav class="submenu">
        <ul class="submenu-items">
          <li class="submenu-item"><a href="#" class="submenu-link">Div 1</a></li>
          <li class="submenu-item"><a href="#" class="submenu-link">Div 2</a></li>
        </ul>
      </nav>
  </ul>
</nav>

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

Issue with GTM: The use of this language feature is restricted to ECMASCRIPT_2015 mode or higher: constant declaration

I'm having trouble extracting UTMs and transferring them to specific fields through my script, but it seems like the script isn't functioning properly on GTM. (Interestingly, the script does work when directly added to webflow custom code) var ...

Retrieve the API Url within an Angular application built with .Net Core

My current setup includes an API project and an Angular Project within the same .NetCore solution. The Angular Project makes API calls to the API project using a baseurl specified in the Environment.ts and Environment.prod.ts files. However, upon publish ...

Angular Datepicker MinDate function prevents selection of dates "behind" by one

I've encountered an issue with the Angular Bootstrap Datepicker where I'm setting the min-date attribute as follows: <input type="text" class="" uib-datepicker-popup="MM/dd/yyyy" show-button-bar="false" ng-model="vm.date" ng-change= ...

Using ReactJS and SCSS to adjust the height: set the height to be twice the size of the element's

Is there a way to increase the height of a div each time it is clicked? I had an idea to add an extra CSS class to a div whenever a button is clicked. Here's how the concept might look: #divToBeDoubled { height: 100px; &.doubleHeight{ ...

Executing a SQL statement effortlessly with the press of an HTML button using PHP

Currently, I am working on a basic PHP website that retrieves a list of salespeople from a MySQL server based on a selection made from a drop-down box. I have successfully added a button next to each result with the intention of running a PHP script using ...

Replace the indexOf() method to be called on a null value

I have discovered a way to override functions in JavaScript, such as indexOf(), like this: var indexOf = String.prototype.indexOf; String.prototype.indexOf = function(){ //MY CUSTOM CODE HERE return indexOf.call(this, arguments); }; By doing this ...

How can I make my opacity change on hover without the need for JavaScript?

I've been attempting to design a book cover that will become fully visible when hovered over, but for some reason it's not working #book_cover { display: block; margin-left: auto; margin-right: auto; width: 25%; height: 71%; ...

Using Angular to showcase the names of uploaded files within an HTML document

I successfully developed an application that uses a post request to upload files to an API. Service file: onFileSelected(event){ this.selectedFile = <File>event.target.files[0]; } onUpload() { const formdata = new FormData(); formdata ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...

Move cursor over the element with a specified attribute

Is it possible to apply a hover effect to an active element without using the disabled attribute? I attempted the code below, but unfortunately, it did not produce the desired hover effect. input.btn:not([disabled]):hover ...

Preventing drag and drop functionality within the knockout js sortable feature

How can I selectively disable drag and drop on certain squares within a 5x5 grid while using the sortable feature in knockout js? Any suggestions or solutions for this specific use case? ...

Is there a way to conceal JSON objects within a three.js scene using the loader.load function?

I am working with multiple JSON files in my three.js project and loading them using loader.load. The files are displayed when I click on the corresponding text content. How can I unload or hide an object with a second click? Below is the code I am curren ...

Obtain the value of a checkbox using jQuery

Here is an example of dynamic checkboxes: <input type="checkbox" checked="checked" value="1" name="user_mail_check[]" class="ami"> <input type="checkbox" checked="checked" value="2" name="user_mail_check[]" class="ami"> <input type="checkbo ...

What is the best way to make a display:flex container grow horizontally along with its wrapped items?

When working with css flexbox, the behavior of the main browsers can vary significantly in certain aspects. For example, I am attempting to build a grid of images: <div class="container"> <div class="photo"></div> <div clas ...

Having issues with my project as the Three.js Scene is malfunctioning and the THREE object is not

My attempt at creating my first three.js project has hit a roadblock. After following a tutorial, I expected to see a black scene upon loading the page, but all I'm getting is a white screen. Errors in Chrome Browser Console: three.js:1 Failed to lo ...

Javascript involved in the process of CSS Background-Images loading after HTML Images

I quickly put together a microsite that is located at . If your internet connection isn't fast or nothing is cached, you may notice that the background-images used for CSS image-text replacement are the last items to load (especially the h1#head with ...

What is the best way to selectively add multiple classes to a single Material UI classes attribute based on certain conditions?

I am trying to use the Material UI Drawer and wish to add a class named "paperStyle" to the classes prop with the rule name "paper" and then, under certain conditions, apply an additional class called "specialPaperStyle" for specific users. However, I have ...

Utilize React Material UI Slider to dynamically adjust Border Radius in your web design

Utilizing React Material UI's components like the slider and button is essential for this project. The main objective is to dynamically change the border radius of the button using the value obtained from the slider. However, there seems to be a chall ...

Incorrect viewport widths in Vue Bootstrap fluid containers

I require a container that spans 100% of the available width until it reaches a specific breakpoint (max-width). Upon exploring the official documentation, I came across the responsive fluid container, which appeared to be a suitable choice. Responsive ...

What makes using $(selector).post() and $.get() in jQuery AJAX so valuable?

While browsing w3school, I came across a discrepancy in the definition of AJAX post and get. Post: $(selector).post(URL,data,function(data,status,xhr),dataType) Get $.get(URL,data,function(data,status,xhr),dataType) Why is there a post method with sel ...