Using jquery for creating a dynamic tree menu

Looking to add a tree menu for this example. Initially all sections should be collapsed. Upon clicking on "Facility," the Buildings should expand in a tree-like format, and further clicks on XYZ building should reveal the Floors. Something along those lines...

Tried using this code, but it's not functioning as expected. Any assistance would be greatly appreciated.

    $('.treemenu').click(function () {
        $(this).parent().children('ul.subtree');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<ul class="treemenu">
    <li>Facility
    <ul class="subtree">
    <li>Building
    <ul class="subtree">
    <li>Royal Building</li>
    <li>Taj Building</li>
    <li>XYZ Building
    <ul class="subtree">
    <li>Floors
    <ul class="subtree">
    <li>1st Floor</li>
    <li>2nd Floor</li>
    <li>3rd Floor</li>
    </ul>
    </li>
    </ul>
    </li>
    </ul>
    </li>
    </ul>
    </li>
    </ul>

Answer №1

  1. Conceal all branches of the tree.
  2. Implement JavaScript that will show/hide tree branches on parent item click.

<style>
    .subtree{
        display: none;
    }
    .treeitem{
        cursor: pointer;
    }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $('.treeitem').click(function () {
            $(this).next('ul.subtree').toggle();
        });
    });
</script>
<ul class="treemenu">
    <li><span class="treeitem">Facility</span>
        <ul class="subtree">
            <li><span class="treeitem">Building</span>
                <ul class="subtree">
                    <li>Royal Building</li>
                    <li>Taj Building</li>
                    <li><span class="treeitem">XYZ Building</span>
                        <ul class="subtree">
                            <li><span class="treeitem">Floors</span>
                                <ul class="subtree">
                                    <li>1st Floor</li>
                                    <li>2nd Floor</li>
                                    <li>3rd Floor</li>
                                </ul>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Answer №2

To start off, the code hides all elements with the class .subtree. Then, when a li element is clicked, it displays the child ul element.

$(".subtree").hide();
$('.treemenu li').click(function () {
  $(this).children('ul.subtree').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="treemenu">
  <li>Facility
    <ul class="subtree">
      <li>Building
        <ul class="subtree">
          <li>Royal Building</li>
          <li>Taj Building</li>
          <li>XYZ Building
            <ul class="subtree">
              <li>Floors
                <ul class="subtree">
                  <li>1st Floor</li>
                  <li>2nd Floor</li>
                  <li>3rd Floor</li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

Answer №3

When looking to implement tree structures in your project, consider utilizing the JSTree library. Comprehensive documentation for this library can be found here. This versatile tool offers a range of customization options and is known for its user-friendly interface.

Answer №4

Just stumbled upon this interesting code snippet:

$('#jqxTree').jqxTree({
  height: '300px',
  width: '300px',
  theme: 'energyblue'
});
$('#Remove').jqxButton({
  height: '25px',
  width: '100px',
  theme: 'energyblue'
});
$('#Remove').click(function () {
  var selectedItem = $('#jqxTree').jqxTree('selectedItem');
   if (selectedItem != null) {
    // Logic to remove the selected item from the tree
    $('#jqxTree').jqxTree('removeItem', selectedItem.element, false);
    // Refreshes the tree after item removal
    $('#jqxTree').jqxTree('render');
}
});
$('#jqxTree').on('removed', function (event) {
   alert("You removed an item");
});

Check out the DEMO here

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

Playback on iPhone devices and Safari experiences a 50% reduction with AudioWorklet

I recently developed a basic audio recorder that utilizes the AudioWorkletAPI. While the playback functions smoothly on Chrome, it seems to have issues on Safari and iPhone devices (including Chrome on iPhone) where half of the audio is missing. Specifical ...

Do not manipulate HTML tags using sed command

There are numerous guides available demonstrating how to utilize sed for modifying/removing HTML tags, and most of them typically suggest something along the lines of... sed 's/<[^>]\+>//g' However, what I am seeking is the opposi ...

Are memory leaks a common issue with Angular directives?

Using a simple html file to replicate a memory leak: <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.min.js"></script> <script> va ...

I'm having trouble getting the aggregation of a child collection to work properly in MongoDB when attempting to apply the $count

Could someone help me troubleshoot my aggregate query? I'm trying to sum the count values for each beacon, but it keeps returning 0. Please let me know if you spot any mistakes in the query. Sample Data [ { ...

Exploring the potential of utilizing the "wait" function in Selenium WebDriver for

I want to automate a test on my website using the Selenium WebDriver for JavaScript. How can I approach running tests here with content that may not be ready when the page loads, such as data coming from an external API? In my case, the content is loaded ...

yet another scenario where the component's state changes without the component reflecting those changes

My react component includes a state variable called: showEditor When showEditor is set to false, the component should display a div containing a number (initially showEditor is false). If the state variable is true, the component should display a textbox ...

Restrict the size of the numerical input in AngularJS

<input class="span10" type="number" max="99999" ng-maxLength="5" placeholder="Enter Points" ng-change="myFunc($index)" ng-model="myVar"> This code snippet adjusts the value of form.input.$valid to false if the number entered exceeds 99999 or is long ...

I require assistance in adjusting my text to properly wrap around the div image

Struggling to make my text fit around the div on this web page. <div id="othermain"> Are you getting ready for your big day? Do you need alterations or remodeling done to your Wedding Dress, Bridesmaid Dress, or any other Bridal Wear? You're in ...

What is the best way to ensure that the HTML and CSS code exported from Figma is responsive

After exporting a Figma design to Angular code, I've encountered challenges in ensuring responsiveness, largely due to the extensive codebase. Media queries have proven ineffective as the majority of the code is written with (px) units and there are c ...

Troubleshooting a Dysfunctioning Character Counter Feature in a JavaScript Input Field

I've been working on a fun little project to practice my JavaScript skills - a plate calculator. Here's the gist: you enter your name, and each letter costs $5, so the total cost of the plate is the length of your name multiplied by $5 (this pro ...

Rendering various models in separate DIVs using Threejs

(Brand new to venturing into Three.js) Overview Currently, I am immersed in the development of a 3D Viewer that can showcase multiple stl models simultaneously. Each model is supposed to be rendered within its own separate div element, resulting in a g ...

Unusual manifestation of the Array

I defined a list array as: list: string[] = []; and added elements to it like this: let infoFile: string = fileReader.result; this.list.push(infoFile); After checking the console log, I noticed something strange [] 0 : "data:image/jpeg;base ...

"Experience the power of utilizing TypeScript with the seamless compatibility provided by the

I'm attempting to utilize jsymal.safeDump(somedata). So far, I've executed npm install --save-dev @types/js-yaml I've also configured my tsconfig file as: { "compilerOptions": { "types": [ "cypress" ...

What are the best practices for implementing Alertify in a Typescript project?

I'm relatively new to Angular2 so please bear with me. I attempted to implement Alertify.js in my Angular2 project for a custom dialog box, but I am encountering difficulties getting Alertify to work properly. Since I lack deep knowledge of JavaScrip ...

Issue with starting React app using the "npm start" command

Upon the installation of a React App, I encountered a error message after executing the command "npm start" Cannot destructure property compile of 'undefined' or 'null'. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href=" ...

Ways to access information from doc.data()

<template> <div> {{ id }} {{ title }} </div> </template> <script> import { useRoute } from 'vue-router' import 'firebase/firebase-firestore' import { db } from '@/fdb' export default ...

Leveraging x-template in VueJS to create a sub-component within a larger component

I'm having trouble understanding how to properly use x-template for a subcomponent within a VueJS component. My component, CategoryNav.vue, has a template that uses an x-template to display a list. However, when I render the page, the component creat ...

The JSON data response is not being properly displayed on the div element

I am having trouble with the success function in my ajax call. The data is processed correctly in the view and the ajax call works fine, but for some reason, the data is not getting appended to the div. Here is my jQuery: $(document).ready(function() { ...

What is causing the error message of "prop id does not match the rendered server output" to appear on my screen?

https://i.stack.imgur.com/VOLDT.png I've been working on a nextjs redux project and I keep running into this error whenever I refresh my page. Despite searching for a solution, I haven't been able to resolve it. The official next js blog suggest ...

Struggling to center a fixed width div horizontally in Internet Explorer

Currently in the process of creating a website template. To see an example, visit Framework Login Page The primary CSS file can be found here: master.css The centralizing of the main parent div is proving to be a challenge. This is the code I am using ...