AngularJS and CSS: A Guide to Effortlessly Toggle Sliding List Elements

I am in the process of developing a drop-down menu that can be clicked. Using my custom AngularJS directive, I have successfully implemented functionality to load menu items dynamically.

While I have made significant progress, I have encountered a small issue.. I am unable to find a CSS(3) only solution for creating an animation when the ul dropdown occurs.

This is what I currently have:

https://i.sstatic.net/6x6Xw.gif

The code snippet for the dropdown function:

private CreateDirective(): any {
        return {
            restirct: 'E',
            scope: {
                dataset: '='
            },
            templateUrl: 'App/Templates/LeftBar/index.html',
            controller: function ($scope) {
                $scope.Select = Select;

                var SelectedItem;

                function Select(MenuItem: any): any {

                    if (SelectedItem != null) {
                        SelectedItem.selected = false;
                    } 

                    if (MenuItem.open) {
                        MenuItem.selected = true;
                        MenuItem.open = false;
                        return;
                    }

                    if (MenuItem.childs && MenuItem.childs.length > 0) {
                        MenuItem.open = true;
                    }

                    MenuItem.selected = true;
                    SelectedItem = MenuItem;
                }
            }
        }
    }

Is there a way to achieve a similar effect to jQuery's slideToggle within my directive?

Thank you for your assistance!

Answer №1

If you want to achieve this effect using only CSS, along with some assistance from Angular for toggling classes, here's how you can do it.

Styling in CSS

.container {
  width: 50px; // Adjust based on your widget width
  overflow: hidden;
}

.content {
   margin-top: 0;
   -webkit-transition: all .3s ease;
   -moz-transition: all .3s ease;
   -o-transition: all .3s ease;
   transition: all .3s ease;
}
.container.collapsed .content {
  margin-top: -100%;
}

HTML Setup

<ul>
  <li class="container" ng-class="{'collapsed':!item.open}">
    <ul class="content">
      <li>...</li>
      ...
    </ul>
  </li>
  ...
</ul> 

This CSS technique involves hiding the UL behind its parent LI by setting a negative margin, causing the UL to move away from its parent block and effectively reducing the size of the parent element.

Answer №2

To add animation to it using only CSS, you can animate the max-height property:

var button = document.getElementById('nav');
button.onclick = function(e) {
  var target = e.target;
  if (e.target.tagName !== 'SPAN') return;
  target = target.nextSibling.nextSibling;
  if (target.className === 'open') {
    target.className = '';
  } else {
    target.className = 'open';
  }
};
ul {
  display: block;
   transition:all 0.5s ease;
}

ul ul {
  max-height: 0;
  overflow: hidden;
}

ul#nav1.open {
  max-height: 50px;
}
ul#nav2.open {
  max-height: 100px;
}
ul#nav3.open {
  max-height: 150px;
}

ul span {
  cursor: pointer;
}
<ul id="nav">
  <li>
    <span>Title 1</span>
    <ul id="nav1">
      <li>one</li>
      <li>two</li>
    </ul>
  </li>
  <li>
    <span>Title 2</span>
    <ul id="nav2">
      <li>three</li>
      <li>four</li>
      <li>five</li>
      <li>six</li>
    </ul>
  </li>
  <li>
    <span>Title 3</span>
    <ul id="nav3">
      <li>seven</li>
      <li>eight</li>
      <li>nine</li>
      <li>ten</li>
      <li>eleven</li>
      <li>twelve</li>
    </ul>
  </li>
</ul>

Please note that I have used max-height instead of height to avoid small pixel discrepancies between browsers. However, different heights need to be set for each navigation option to ensure smooth animation effects.

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

Retrieve a specific subdirectory from the bundle

I've developed a Typescript package with the following file structure: package.json src/ index.ts common/ index.ts sub/ index.ts My goal is to import certain modules from the package like this: import {...} from '<package>&ap ...

Hide the search popup when the user clicks on the "find" button within the jqgrid

What is the solution to closing the search popup when clicking on the Find button? When I search for data in jqgrid and click on the Find button, the Search popup remains open even though the data has been filtered. How can I close the popup after searchin ...

Ensuring a response is sent back only after a loop has completed in NodeJs

Struggling to properly format the logic in order to send back a fully populated array of objects after a GET request to a specific URL. The goal is to take the "connections" array from the user making the request, extract the connection's name and pic ...

Learn how to utilize Jquery to create a dynamic slide effect that toggles the

I am looking to change a banner on click functionality. Currently, I have hidden the 2nd banner and banner 1 is displayed. When the arrow is clicked, I want banner 1 to hide and banner 2 to show. The challenge is that I attempted using HTML for this task. ...

Does WebSVG struggle with producing sharp, defined lines in its inline format?

Upon page load, my SVG background starts as separated and then smoothly transitions into forming the background. However, I noticed that a large triangle with poor quality and choppiness appears at the beginning. What could be causing this issue? For an e ...

Utilize Content Delivery Network Components in Conjunction with a Command Line Interface Build

As we progress in building our Vue applications, we have been using the standard script tag include method for Vue. However, as we transition from jQuery/Knockout-heavy apps to more complex ones, the maintenance issues that may arise if we don't switc ...

Unable to upload file to firebase storage - encountering technical issues

After following the documentation on firebase storage, I still can't seem to get my file upload to work properly. Using react, my goal is to successfully upload a file to firebase storage. However, I keep encountering an error message: TypeError: th ...

What is the process of converting a `typeorm` model into a GraphQL payload?

In my current project, I am developing a microservice application. One of the services is a Node.js service designed as the 'data service', utilizing nestjs, typeorm, and type-graphql models. The data service integrates the https://github.com/nes ...

Guide on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

Firefox not displaying caret in Bootstrap dropdown

I am trying to display a caret on the right side of a bootstrap dropdown button inside a button-group. Here is the code snippet I am using: <div class="span3 well"> <div class="btn-group btn-block"> <a class="btn btn-primary dro ...

Conflicting issues with jQuery's load() method

I am facing an issue with loading two HTML pages into a single div. I have index.html and try.html in the root folder, where try.html is loaded into index.html's div (#content) when Button 01 is clicked on index.html. The problem arises when I further ...

Enhancing the Syntax of If and If Else in Jquery Functions

I'm struggling to simplify and optimize this block of code. Would appreciate any help in making it more efficient! var status = "closed"; $(document).on('click', '[data-toggle-nav]', function(event) { if ($(this) && status = ...

Inheritance-based generic type inference in Typescript

Take a look at this piece of code: class A<T> { t?: T; } interface B {} class C implements A<B> {} function f<T1 extends A<T2>, T2>(a: T1): T2 | undefined { return a.t; } const result = f(new C()); const result2 = f(new A<B> ...

Three.js: Wanting to create objects and add motion along a curved path

In an attempt to create a unique effect, I am exploring the idea of spawning a series of objects on a setInterval and assigning each object a customized animation on a path using requestAnimationFrame. I have successfully added one object and animated it a ...

What is the method for including a hyperlink in an swf document?

I've been working with HTML and trying to embed links in my webpages that are in offline mode. After doing some research, I came across the following code snippet: MyClickTagButton.addEventListener( MouseEvent.CLICK, function():void { if (roo ...

Guide for bringing in a complete npm library into React Native beyond just a single file access

Currently, I am facing an issue with importing the sjcl library into my project. Even though there are multiple files within the library, I am only able to import one file successfully. This is what I have tried from the command line: npm install sjcl -- ...

How can I hide a root layout component in specific nested routes within the app directory of Next.js?

Is there a way to prevent rootlayout from being wrapped around dashboardlayout? Explore the latest documentation for Next.js version v13: https://i.sstatic.net/M0G1W.png Take a look at my file structure: https://i.sstatic.net/nVsUX.png I considered usi ...

When dalekjs attempted to follow a hyperlink with text in it, the link failed to function properly

My goal is to retrieve an element from a list by clicking on a link containing specific text. Here is the HTML code snippet: <table> <td> <tr><a href='...'>I need help</a></tr> <tr><a href=&a ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

Why is it necessary to call the .call(this) method when extending a THREE.js "class"?

Currently, I am in the process of creating a new object that should inherit from THREE.Object3D(). In my code snippet, you can see how I have set it up: function myNewObject() { THREE.Object3D.call(this); //... } myNewObject.prototype = new THREE.O ...