Angular provides a convenient way to close a div when clicking outside of it

One thing to keep in mind with jQuery is the ability to close a div when clicking outside of it.

 $(document).on("click", function (e) {
        if (e.target.id != "user-login-top" && !$(e.target).closest("#user-login-wrapper").length) {
            $("#user-login-wrapper").removeClass("wide");
        }
    });  

Is there an equivalent solution in Angular?
Check out this Fiddle

Thank you in advance.

Answer №1

By creating a personalized directive, you can now hide the right sidebar by clicking outside of the top menu.

For a demonstration, visit: http://jsfiddle.net/zqdmny41/20/

app.controller('mainCtrl', function ($scope) {
    // Function to toggle off the right sidebar.
    $scope.hideSideMenu = function() {
        $scope.bodyCon = false;
        $scope.noneStyle = false;
    }
    ...
})
.directive("outsideClick", ['$document', function( $document){
return {
    link: function( $scope, $element, $attributes ){
        var scopeExpression = $attributes.outsideClick,
            onDocumentClick = function(event){
                if(event.target.id != 'rightMenu' && event.target.id != 'toggle-menu') {
                    $scope.$apply(scopeExpression);
                }
            };

        $document.on("click", onDocumentClick);

        $element.on('$destroy', function() {
            $document.off("click", onDocumentClick);
        });
    }
}
}]);

In your HTML:

<aside class="rightbar" id="rightMenu" ng-class="{'noneStyle' : noneStyle}" outside-click="hideSideMenu()">

This implementation allows for:

  • Toggling the right sidebar by clicking the top icon,
  • No action when clicking on the right sidebar itself,
  • Hiding the right sidebar by clicking elsewhere.

The key concept involves:

  • Developing a custom directive named "outsideClick" and attaching it to the right sidebar menu with the attribute outside-click="hideSideMenu()"
  • Passing the function name hideSideMenu to the directive, which binds a click event to the document.
  • If a user clicks anywhere on the page and the target ID is neither rightMenu nor toggle-menu, the right sidebar will be concealed.

Source:

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

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

What is the best way to invoke a controller method using jQuery within a cshtml file?

I am working on a project where I need to add user information to the database by calling a function in my controller class. The user's information is entered through a form created in a .cshtml file that interacts with an external JavaScript file. Is ...

Is it possible to access the ID element of HTML using a variable in jQuery?

I have fetched some data from a JSON ARRAY. These values include Value1,Value2, and Value3. Additionally, I have an HTML checkbox with an ID matching the values in the array. My goal is to automatically select the checkbox that corresponds to the value re ...

Loading GLTF model via XHR may take an infinite amount of time to reach full completion

I am attempting to load a GLTF model of a piano using XHR and showcase the loading progress on a webpage. The model is being loaded utilizing the Three.js library. On a local server, everything works perfectly - the loading percentage is shown accurately, ...

Implementing varied constants in AngularJS application for production and development using webpack

I am trying to adjust the URL for an external API in my AngularJS app depending on whether it is running in development or production mode: Here is a snippet from my app.js file: var API_URL = 'http://localhost:8000/api'; # dev configuration ...

Tips on arranging two buttons vertically so that they each occupy 50% of the total height

I am looking to create + and - buttons in Bootstrap where the + is stacked on top of the - with both buttons occupying 50% of the height of the full div each. Here's an example of what I would like to achieve: https://i.sstatic.net/DrnEt.png To imp ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Managing two React clients simultaneously using PM2

Is there a way to run multiple clients using npm start on pm2 by creating an alias for each of them? I've been attempting to use the command pm2 start npm for both, but it seems to only start one and ignore the other. ...

Column Flow in CSS Grid: Maximizing Auto-Fit - How to Optimize Row Layouts?

Having some trouble understanding how auto-fill and fit work in grid layouts. I am familiar with basic CSS, but new to working with grid layouts. I have a set of checkbox items with labels that I want to display in columns depending on screen size, with c ...

What is the mistake in my update function when working with nodejs and mongodb?

Greetings! I am a beginner in using nodejs and mongodb, and I am looking to create a function that updates the win, lose, and draw record in my userschema. Here is my Schema: UserSchema = new mongoose.Schema({ username:'string', passwor ...

Steps for adding an npm dependency as a peer dependency:

Is there a way in npm to install dependencies as peer-dependencies similar to the yarn option --yarn, rather than manually adding them? For instance: "peerDependencies": { "@angular/core": "^7.0.0" } Update: Further clarifi ...

Update the picture and assign a class for the currently selected menu or button

I am currently working on creating interactive buttons that change an image when hovered over and clicked. The active button should have a specific class applied to it, which will be removed once another button is clicked. However, I have encountered some ...

"Looking to design a custom UI component complete with animations? Here's how to bring your

I attempted to implement the card component, gradient background, and animation but fell short of achieving the desired outcome as seen in the gif. How can I enhance the smoothness of the animation, replicate the exact gradient, and ensure the card stands ...

External script implementing StratifiedJSIt is possible for an external script

Recently, I stumbled upon the amazing StratifiedJS library that offers many features I find essential. It functions flawlessly when implemented directly in my HTML file, like so: <script src="libraries/stratified.js"></script> <scr ...

Using conditional routing for nested routes in VueJS

Is there a way to conditionally redirect a children route? I've experimented with various methods but haven't had any success. Currently, I am using a state from the store as the condition to redirect the children routes. I have exported my stor ...

Unlock the power of React Native by learning how to implement multiple routes within your

//Prev.jsx const handleClick = (row) =>{ const orderNumber = row.orderNumber.replace(/\D/g, '') console.log(orderNumber) navigate("/drivers/" + (driverId) + "/" + (orderNumber)) } //App.js <BrowserRouter& ...

Steps for displaying an error message in a method that returns a ResponseEntity in Spring MVC using the @ControllerAdvice annotation

Currently, I am in the process of developing a web application using Spring MVC and AngularJS. For this project, I am creating a Rest API that returns ResponseEntities containing JSON strings. One issue I am facing is how to handle exceptions within my ap ...

How can I send the innerText of an AngularJS directive to a template?

How can I pass the innerText of an AngularJS directive to a template? Screenshot: https://i.sstatic.net/v32xH.jpg Here is the HTML code: <div class="carBox"> <img ng-src="img/{{Id}}.png" width="128" height="128" /> <br /> <br ...

Is there an issue with Vue 3's v-model not updating correctly in Chrome on Android devices?

In my project, I have developed a unique component that functions as a combination of an input and select field. This allows users to input text into the field and select items from a dropdown menu based on their query. The component works flawlessly on m ...