When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someone clicks on the appropriate title. I have successfully implemented the functionality for the first sublevel. It shows up and disappears when its 'parent' is clicked. However, whenever I attempt to click on a title within the sublevel, the sublevel closes instead of opening the next one. I know there must be an error in my approach, but I can't seem to figure out what it is :( I've compiled all of my code here: http://jsfiddle.net/kyqJ6/, but for some reason, it doesn't work there even though I copied it exactly as is. Here's an example of the javascript segment:

function dropdown1()
    {
        if(document.getElementById('menu1').style.display=='block'){
            document.getElementById('menu1').style.display='none';
        }
        else{ 
            document.getElementById('menu1').style.display='block';
        }
    };

I understand that there may be mistakes in my code and many areas where improvements could be made. Please don't hesitate to point those out. However, at this point, what I really need help with is resolving the issue mentioned above :) Thank you for taking the time to read this, and in advance, thank you for any help or advice you can provide!

Answer №1

At first, the issue with your jsfiddle not working properly is due to how you have set up the script loading. Changing it to "No wrap - in <head>" instead of onLoad should resolve this.

Secondly, what you are experiencing is a result of something known as propagation. To understand this better, consider two objects, A and B:

--------------------
|A                 |
|     --------     |
|    |B       |    |
|    |        |    |
|     --------     |
|                  |
--------------------

Basically, all events in the DOM bubble up through the parent objects. So when clicking on A, clickA() will trigger. However, when clicking on B, both clickB() and then clickA() will be triggered because B is a child object of A. This jsFiddle example demonstrates this concept by logging events in the console. Therefore, even though your sub-level dropdowns do show up initially, clicking on their parent dropdown labels hides everything (expanding the sub-level dropdowns again upon re-clicking).

If you want more detailed information about this, check out this blog post I wrote previously. The referenced jsFiddle there offers a visual aid.

In essence, you have two choices:

  • Remove the sub-level dropdowns as children of their parent dropdowns and position them so they still appear nested.
--------------------  --------
|A                 | |B       |
|                  | |        |
|                  |  --------
|                  |
|                  |
|                  |
--------------------

OR (recommended for minimal code alteration)

  • Utilize the stopPropagation() method to halt event bubbling. By applying this to each click event, you can prevent further bubbling. Check out the modifications made in this updated jsFiddle where stopPropagation() is added to the dropdown2() method.

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

Incorrect height of div on iPhone 6 and 7 is observed when utilizing flexbox and setting the height to 100% dimensions

I'm experiencing an issue with the display on iOS devices, specifically iPhone 6 and 7. I am creating a news card layout where I set the content height to 100%. However, on these specific iPhone models, the height is being displayed incorrectly (as se ...

Extracting Client's True IP Address using PHP API

Utilizing the following api: I am able to retrieve country, city, and real IP address in localhost (127.0.0.1) successfully. However, when I implement this code on my website, it displays the server's address instead of the client's. How can I r ...

Verify whether an option is chosen in CakePHP 3 form

I'm working on a form where users can select Types and each type has an associated color. In my TypesController, I have a function that retrieves the list of types with their IDs, names, and colors. $types = $this->Types->find('list') ...

Using NodeJs to Render HTML Templates and Implement Logic on the Server Side

Hello, I am currently working on developing a widget module for my Angular 1 based UI project. This widget is meant to display real-time information. My design involves sending an HTML view to the client from the Node server (potentially using Express.js) ...

How can I remove a dynamically added <tr> element using jQuery?

I insert the <tr> into the <tbody> for (var i = 0 ;i < 12 ;i++){ $(`<tr><td>test</td></tr>`).appendTo('#songsTbody'); } within this HTML structure. <tbody id="songsTbody"> </tbody> ...

Div blur event for editing content

Utilizing a content editable div as an input control has presented some challenges for me. Unlike a textarea or input element, the div does not send information to the server automatically. To work around this issue, I have implemented a solution where I u ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Is it necessary to mark all checkboxes in the initial column of the gridview?

I have encountered an issue with my code that checks all checkboxes in the first column of a gridview. It seems to work only for Internet Explorer versions 5.0 to 8.0, but gives a Javascript error when running on IE 9 and above stating "Function Expected ...

Go back to the previous operation

Utilizing ajax to verify if a username is available by checking the MySQL database. If the username is already taken, it will return false to the form submit function. index.php $("#register-form").submit(function(){ var un = $("#un").val(); $.aj ...

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

What is the best way to incorporate jQuery's default handsontable into an AngularJS directive?

I currently have a handsontable functioning in a non-AngularJS application, and I am in the process of developing a new version of the software that heavily utilizes AngularJS (SPA). My question is: is it possible to encapsulate the existing handsontable ...

EventBus emitting multiple times until the page is refreshed

Trying to make use of the EventBus in Vue.js to transfer data from one method to another. In my setup, I've got two methods named one() and two(). Here's how I'm implementing the EventBus: one() { EventBus.$emit("this:that", data); } And ...

Do not need to refresh the form

I developed a PHP-based Feedback form that includes a Popup from Foundation 5. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> .auto-style1 { margin-left: 1px; ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

Progress bar indicating the loading status of an AJAX script

I am facing a challenge with creating a progress bar in AJAX. The entire page is loaded through AJAX, and one of the webpage elements uses AJAX to fetch large rows from the database. I have attempted to implement a progress bar within this script using a ...

Align images to the bottom of the gallery only if their heights differ

I'm currently working on an image gallery project and have encountered a problem. When all the image labels are of the same length, they align perfectly. However, if the label is longer than one line, it causes the image to move up instead of creating ...

Unusual default Nav bar positioning

When attempting to create a navbar, I encountered small gaps that seemed impossible to close. Adjusting margins only resulted in new gaps appearing on the opposite side. Even when trying to find a compromise, I ended up with gaps on both sides instead. It ...

What is the method to determine the size of a file in Node.js?

Have you ever wondered how to accurately determine the size of a file uploaded by a user? Well, I have an app that can do just that. The code for this innovative tool is provided below: Here is the snippet from server.js: var express = require('expr ...