AngularJS closes when clicked outside

I've been attempting to add a close on outside click functionality to my code, similar to this example: http://plnkr.co/edit/ybYmHtFavHnN1oD8vsuw?p=preview

However, I seem to be overlooking something as it's not working in my implementation.

HTML Directive

<div class='multiDate'>
 <div class="dropdown">
  <button data-ng-click="show = !show" class="dropbtn">Press</button>
  <div id="myDropdown" ng-show="show" class="dropdown-content">
   <multiple-date-picker></multiple-date-picker>
  </div>
 </div>
</div>

HTML Main

<html>

 <head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5f50594b525f4c544d7e0f1008100c">[email protected]</a>" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
  <script data-require="moment.js@*" data-semver="2.14.1" src="https://npmcdn.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b9bbb9b1baa094e6fae5e0fae5">[email protected]</a>"></script>
  <link rel="stylesheet" href="style.css" />
  <link rel="stylesheet" href="https://arca-computing.github.io/MultipleDatePicker/stylesheets/multipleDatePicker.css" />
  <script src="https://arca-computing.github.io/MultipleDatePicker/javascripts/multipleDatePicker.min.js"></script>
  <script src="script.js"></script>
 </head>

 <body ng-app="app" ng-controller="cntrl">
  <multi-date></multi-date>
 </body>

</html>

JS

var app = angular.module("app", ['multipleDatePicker']);
app.controller("cntrl", function($scope) {
});

app.directive('multiDate', function($document) {

  return {
    templateUrl: 'multi.html',
    replace: true,
    link: function(scope, element) {

      $document.bind('click', function(event) {
        var isClickedElementChildOfPopup = element
          .find(event.target)
          .length > 0;

        if (isClickedElementChildOfPopup)
          return;

        scope.show = false;
        scope.$apply();
      });
    }

  }

});

PLNKR

Answer №1

Your Plunker code is almost there, but there's one issue - the jQuery library isn't referenced. Make sure to include it before the Angular library in your HTML.

<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0b040d1f060b1800192a5b445c5448405d">[email protected]</a>" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
    <script data-require="moment.js@*" data-semver="2.14.1" src="https://npmcdn.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="781517151d160c384a56494c44445359">[email protected]</a>"></script>

If you don't include jQuery before Angular, Angular will default to using its built-in jqLite, which doesn't provide all the functionality of jQuery's element.find function.

Answer №2

Let's start with angularjs which typically utilizes jquery that is incorporated into the page before angularjs, or alternatively, uses jqLite.
Furthermore jqLite may not have all the methods available in jquery, and in some cases, their behaviors may vary. For more information, check out the documentation for angular.element.

Your example isn't functioning properly because of

find() - Limited to lookups by tag name
. To resolve this issue, consider modifying the condition for isClickedElementChildOfPopup using one of the potential solutions below:

var isClickedElementChildOfPopup = event.target.closest(".dropdown") !== null;

However, keep in mind the Browser support for the closest method and the need for a polyfill.

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

Struggling to configure Velocity Js?

After attempting to use Velocity Js for the first time, I encountered some issues while trying to create a navigation menu. Despite having functioning code and animations, the menu failed to open. I followed the instructions on the Velocity JS site by incl ...

JavaScript-powered dynamic dropdown form

I need help creating a dynamic drop-down form using JavaScript. The idea is to allow users to select the type of question they want to ask and then provide the necessary information based on their selection. For example, if they choose "Multiple Choice", t ...

Validating whether another element is checked when a radio button is unchecked

I'm completely stuck on this issue - I just can't figure out how to dynamically change the image when a user unchecks a radio button (i.e., checks a different radio button). Here is the code: handleCheckbox = e => { let target = e.targe ...

ChartJS, introducing a new dataset

I'm looking for a way to showcase my 3 curves in a specific order: start with the first one, then after a 5000 interval, add the second curve, and finally, after another 5000 interval, include the third dataset. The code below currently updates a sin ...

Trigger JavaScript code following a specific occurrence

Struggling to find a solution due to my limited knowledge in JS, I've decided to pose the query myself: How can I trigger my JavaScript after a specific event? With a form in place, I aim for the JS to execute once the final radio button is selected b ...

Tips for sending information from a controller to jQuery (Ajax) in CodeIgniter

Code snippet in controller: $rates['poor'] = 10; $rates['fair'] = 20; $this->load->view('search_result2', $rates); //Although I have attempted different ways, the only successful method is using the code above. Other ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...

Assistance required in filling out a table solely through JavaScript with input from an HTML form

Hello, I am currently pursuing a second career and have just started learning HTML & JavaScript. For a simple assignment, I need to take user input in the form of numShares and numYears through HTML. My goal is to use JavaScript to populate a 3-column tabl ...

How to Programmatically Disable OnClick Functionality in a Nested Div Using JavaScript and jQuery

I'm currently working on a Javascript application that allows users to enable/disable controls dynamically. While I've had success in disabling/enabling nested inputs and buttons, I'm facing an issue with disabling an onclick event within a ...

Randomize checkbox selection using Javascript and Bootstrap

I'm in a bit of a bind with my webpage and could really use some help to figure it out. Here's the issue: On my website, there's a table of players. Each player has two checkboxes on their line: one to show if they are active (checked), and ...

JS Issue with Countdown functionality in Internet Explorer and Safari

I am having an issue with a JavaScript countdown not working on Internet Explorer and Safari, despite being tested on Windows 7. It works fine on Chrome and Firefox. I am unable to switch to a jQuery countdown due to certain restrictions on the website, so ...

What could be the issue with this C# GridView code snippet?

I am facing an issue with a GridView that contains checkboxes. When I try to select a checkbox, I need to retrieve the values from that specific row. The problem lies in the fact that the chk variable in my C# code never evaluates to "true," preventing the ...

Executing unique calculations on Kendo UI Grid Columns

For experienced users, this may seem simple, but as a newcomer, I'm struggling with a basic arithmetic task. I want to multiply one of the column values (DealValue) by 0.05 in my Kendo grid setup. Despite looking through the Kendo docs, I couldn' ...

Error encountered in Vue3: An uncaught TypeError occurred when attempting to "set" a property called 'NewTodo' on a proxy object, as the trap function returned a falsish

I encountered an error message: Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'NewTodo' This error occurs when attempting to reset the input text value within a child component (FormAddTodo.vue). App.vue: expo ...

Angular's $routeProvider fails to navigate

I'm facing an issue with my Angular JS application where the $routeProvider doesn't load the template in the ng-view section. I have set up <html data-ng-app="myApp"> and <section data-ng-view></section. The template doesn't ...

Exploring the efficacy of unit testing on Express controllers

After days of working on this, I've hit a wall and finally decided to ask for assistance. Everything runs smoothly when the server is up and API calls are made. However, when attempting to unit test the controller, I encounter some issues. I'm ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

Encountering an NPM error while attempting to initiate a new React application

Having trouble creating a React app due to an npm warning message? Seek assistance, please! npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19342d2e6a6867687c4b">[email protected]</a>: This ve ...

Removing an item from an array depending on a specific condition and index

I am working with an array structure that looks like this: [ {key: 4, data: {…}, qText: {…}}, {key: 4, data: {…}, qText: {…}, isVisible: false}, {key: 5, data: {…}, qText: {…}, isVisible: false}, {key: 4, data: {…}, qText: {…}, isVi ...