Tips for automatically closing a drop-down menu by clicking anywhere on the page

Hey there, I'm currently working on developing a Single Page Application (SPA) in AngularJS. After a user successfully logs in, I am creating a dropdown menu in the upper right corner that expands when clicked. However, I'm trying to figure out how to close the dropdown whenever the user clicks anywhere else on the page.

Below is the code snippet for generating the dropdown:


var id = document.getElementById('ProfileDropdown');
        id.innerHTML = $scope.ProfileDropdown = '  <div data-drop-down>' + ' <ul>' +
                '<li ><a ui-sref="Dashboard.Userprofile">User Profile</a></li>' +
            '<li><a ui-sref="Dashboard.changepassword">Change Password</a></li>' +
              '<li><a ui-sref="Dashboard.LeaseListings">Lease Request</a></li>' +
                 '<li><a ui-sref="#">Service Request</a></li>' +
                   '<li><a ui-sref="Dashboard.NewServiceRequest">New Service Request</a></li>' +
           ' <li ng-click="logout()">Logout</li>' +
        '</ul>' + '</div>';
        $compile(id)($scope);

I'm having trouble figuring out how to implement the functionality to close the dropdown when the user interacts with any other part of the page.

Since this is a SPA with only one HTML page and using UI-routing to dynamically load content, could you please provide some guidance on how to solve this issue?

Any assistance or suggestions would be greatly appreciated!

Thank you for your help.

Answer №1

Give this a shot

   $document.click((e) => {
    let element = angular.element('.enterElementClassName')
     if (!element.is(e.target) && element.has(e.target).length === 0)      {
        // execute close popup logic
    }
    });

Answer №2

To achieve this in Angular, you can refer to a helpful guide on Adding and Removing Classes in Angular. Utilize the $scope.class method to effectively remove the class of the Dropdown, thereby hiding or removing it from the Web Page.

Alternatively,

In terms of Javascript/JQuery,

There are multiple approaches to closing a drop-down menu. Assuming there is a specific class assigned to the element representing the dropdown:

var id = document.getElementById('ProfileDropdown');
        id.innerHTML = $scope.ProfileDropdown = '  <div data-drop-down class="dropdown_menu">' + ' <ul>' +
                '<li ><a ui-sref="Dashboard.Userprofile">User Profile</a></li>' +
            '<li><a ui-sref="Dashboard.changepassword">Change Password</a></li>' +
              '<li><a ui-sref="Dashboard.LeaseListings">Lease Request</a></li>' +
                 '<li><a ui-sref="#">Service Request</a></li>' +
                   '<li><a ui-sref="Dashboard.NewServiceRequest">New Service Request</a></li>' +
           ' <li ng-click="logout()">Logout</li>' +
        '</ul>' + '</div>';
        $compile(id)($scope);

To close the dropdown, trigger an event that targets the main wrapper of your HTML markup and removes the dynamically added class from the div. Handling the removal/closing of the element/class falls outside the scope of this question; additional guidance can be found at this link.

We hope this information proves beneficial.

Best Regards,

Shohil Sethia

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

Turning off devtools in Next.js

Currently, my focus is on developing an application using Next.js and I am in search of a way to prevent the opening of devtools. While exploring npm packages, I came across a promising tool called Disable-devtool - npm link. However, Next.js keeps present ...

The error message: "Trying to access property 'get' of an undefined object"

$http.get('/contactList'). success(function(data){ console.log('received data from http get'); }). error(function(data) { $scope.error = true; $scope.data = data; return 'error message'; }); There seems to be ...

Update the class of the element that is currently selected using jQuery and the `this` keyword

Is there a way to change the class on hover only for the current element using 'this'? The code I have changes classes for all elements, but I need it to work individually. Here is the code snippet I'm currently using: https://codepen.io/ky ...

Infinite loop occurring when setting state to child component in React

On a page featuring dropdown menus for content searching, the dropdown is non-functional but provides context. This page serves as a listing page. After performing calculations on the listing page and updating the state, I encounter an infinite loop when ...

Can jQuery.jScrollPane be set to consistently display a vertical scroll bar?

Can jQuery.jScrollPane be configured to consistently display a vertical scroll bar? Is there a hidden setting or API function that can achieve this? Ideally, without needing to adjust the content pane's height or other properties. ...

Storing information in a parse table using NodeJs

I am trying to add data to a Parse table. At the top of my code, I have the line import Parse from 'parse/node';. Here is how I am inserting the data: const game = Parse.Object.extend('Game'); const query = new Parse.Query(game); que ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

ReactJS safeguarded route redirection/refresh obstacle

Utilizing react and react-router-dom: import React from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; To secure a route with the following: Router const Router = () => { return ( <Switch> ...

``Using backticks to denote HTML syntax - Leveraging Google Charts to create

Has anyone found a way to incorporate HTML in ticks within a Google chart? I am attempting to insert a weather icon from This is my current attempt: const dailyData = new google.visualization.DataTable(); dailyData.addColumn('timeofday' ...

How about displaying the Ajax response as an image?

I'm working on a script that pulls an image link, which seems to be functioning correctly. However, I am struggling with how to display the link as an image. Can someone please assist me with this? <script src="//ajax.googleapis.com/ajax/li ...

Remove the default selection when a different option is chosen using Bootstrap

I have implemented the Bootstrap-select plugin () for a multiple select dropdown on my website. Upon page load, there is a default option that is already selected. See image below: https://i.stack.imgur.com/SzUgy.jpg <select id="dataPicker" class=" ...

Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout: src components Footer.vue views Page.vue App.vue I want to access the 'message' vari ...

Just built a React App including a blog functionality, but for some reason the blog posts are not showing up. Any suggestions on how to fix this issue

I'm currently working on a project that involves creating a blog page for our react app. Despite my efforts, I am facing difficulty in getting the blog posts to show up. In order to retrieve all the posts from my MYSQL database, I have set up an API ...

Node.JS 3DES encryption encountering an issue with IV length validation

I'm new to working with Node.js and I've encountered an issue with the encryption object: var des3_key = new Buffer("redacted", "base64"); // obtained from another source var des3_iv = new Buffer("alsoredacted", "base64"); // obtained from anoth ...

What happens when tabs are dynamically added on keypress?

I am encountering issues with this code snippet. $('body').on("keypress", ".message", function(e) { if ( e.keyCode == 13 && $(".message").val().length > 0 ) { input = $(".message"); // Check for join com ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

AngularJS encountered an error while attempting to create a module with obfuscated code, resulting in a $injector:

Attempting to obfuscate my angularjs application using mangling is resulting in an error. I have been advised to use ngmin to address this issue. Following this advice, I have successfully used ngmin to properly encapsulate my controller code within an arr ...

Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo https://i.stack.imgur.com/Yt4ya.png Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Mater ...

Enhance the user experience with a personalized video player interface

I am facing difficulty in creating a responsive video with custom controls. While I understand that using a <figure></figure> element and setting the width to 100% makes the video responsive, I am struggling with making the progress bar also r ...