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

The Bulma calendar date input fails to display the pre-filled start date

I am facing a challenge while trying to integrate the Bulma calendar into my project, particularly when it comes to setting a default start date. According to the documentation, I am using the following method: <input type="date" data-start-date="10/2 ...

An external script containing icons is supposed to load automatically when the page is loaded, but unfortunately, the icons fail to display

Hello and thank you for taking the time to read my query! I am currently working in a Vue file, specifically in the App.vue where I am importing an external .js file containing icons. Here is how I import the script: let recaptchaScript2 = document.creat ...

Output PHP variable in JavaScript (and show the value within an iframe)

I'm trying to retrieve a value from a MySQL database using PHP, store it in a variable, output the PHP variable in JavaScript, and then display the value in an iframe. However, I'm having some trouble getting it to work... Here is my PHP code: ...

Error message appears when attempting to duplicate vertices in a THREE.Geometry object: 'Vector is not defined'

I am attempting to dynamically add new faces to a mesh, but I keep encountering a console warning: THREE.BufferAttribute.copyVector3sArray(): vector is undefined Despite the warning, this example successfully generates a single triangle that is a repli ...

What will occur if I use an XMLHttpRequest to request a file that is currently being downloaded?

My goal is to enhance links in a progressive manner using the PJAX style. My plan was to layer this on top of some regular prefetch <link>s: <link rel="prefetch" href="next.html"/> If the browser has already downloaded next.html, then the PJA ...

Determine using Lodash whether there is an object in an array that matches the ID from a separate array

There is a user array defined as follows: var users = [{ id: 1, name: 'ABC', isDisplay: true }, { id: 2, name: 'XYZ', isDisplay: true }, { id: 3, name: 'JKL', isDisplay: true }]; Additionally, there is another arra ...

The instance is referencing "underscore" during render, but it is not defined as a property or method

I have experience as a skilled react developer, but I've taken over a vue.js project from another developer and managed it for quite some time. Regrettably, I haven't put in the effort to learn vue properly. When using lodash, I encountered an u ...

Stopping the loop: Disabling the SetInterval function with ResponsiveVoice code in JavaScript

Currently, I am developing a queuing system and implementing voice announcements using Responsive Voice. I have used setInterval, but the issue is that the voice keeps looping without stopping. $( document ).ready(function() { setInterval(function() ...

Transferring a JSON value to PHP and saving it in a MySQL database

I currently have JSON values stored in a variable called json_obj in JavaScript. My goal is to pass this data on submission and store it in a MySQL database using PHP. However, I am unsure of how to achieve this. var json_obj = [ {"id":"1","name":"mun ...

Unique background image for every individual page

For my mobile app development using Jquery Mobile, I have implemented a custom theme but now want to vary the background images for different sections. My current code looks like this: .ui-overlay-a, .ui-page-theme-a, .ui-page-theme-a .ui-panel-wrapper { ...

How can I incorporate a vertical line divider and a legend into a curved box using HTML and CSS?

https://i.sstatic.net/dj4zb.png I have this image that I need to divide into three sections with a legend at the top, similar to the image shown. So far, this is the code I have, but I'm struggling with creating the vertical line, adding space betwe ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

Iterating over an array of objects and executing asynchronous operations

I am currently working with NextJS and managing an array of assets (images) within my state. The task at hand is to post these images to the API. To accomplish this, I have a specific object that handles the posting process using the following syntax: let ...

Is there someone who can explain to me the process behind this?

(function(ng, app){ app = angular.module('app', []); app.config(function($provide) { $provide.constant('town', 'Burlington'); }); app.constant('name', 'Rob F.'); app.controlle ...

Jquery's ajax function is failing to execute the server side function

I have a specific structure for my solution: My goal is to execute the recommendationProcess function from CTL_RateRecommendationDetails.ascx.cs in CTL_RateRecommendationDetails.ascx Therefore, I wrote the following code: $.ajax({ type: "POST", ...

Concealing excess content in a vertical container with margins

I'm currently working on setting up a grid of thumbnails for my blog posts using Bootstrap 4. The columns have a size of col-md-6. Within each column, there is an anchor with a background image and a gradient overlay that transitions from black to tr ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...

Ways to hide notifications by setting a timer while keeping the delete option visible

Presently, this is the code I am working with using Javascript and Vue.js. I have an array called Messages.length that contains messages. When the x button is clicked, it triggers the "clearMessages(item)" function on the server side. However, I also aim ...

Remove a row from a Jquery Jtable

I am running into difficulties when trying to delete rows, and I suspect that the issue might be related to the post[id] not being properly sent. Although the delete message appears, the row is not actually deleted. Below is the snippet of my code: JAVASC ...