How to close div when div loses focus?

advertisements

I made a simple plunkr here http://plnkr.co/edit/zNb65ErYH5HXgAQPOSM0?p=preview

I created a little datepicker I would like this to close itself when you focus out of it (focusout of datepicker) if I put blur on input I'm unable to use the datepicker, if I put focusout event on datepicker it doesn't works

I also tried:

angular.element(theCalendar).bind('blur', function () {
    $scope.hideCalendar();
});

but it doesn't work.

Any clue?


this is because you are removing the item before you get a chance to do anything, here is a working example:

http://plnkr.co/edit/mDfV9NLAQCP4l7wHdlfi?p=preview

just add a timeout:

thisInput.bind('blur', function () {
  $timeout(function(){
    $scope.hideCalendar();
  }, 200);
});

have you considered using existing datepickers? like angularUI or angular-strap: http://mgcrea.github.io/angular-strap/##datepickers

Update:

Not a complete solution, but should get you quite closer:

    angular.element($document[0].body).bind('click', function(e){
      console.log(angular.element(e.target), e.target.nodeName)
      var classNamed =  angular.element(e.target).attr('class');
      var inThing = (classNamed.indexOf('datepicker-calendar') > -1);
      if (inThing || e.target.nodeName === "INPUT") {
        console.log('in');
      } else {
        console.log('out');
          $timeout(function(){
            $scope.hideCalendar();
          }, 200);
      }
    });

http://plnkr.co/edit/EbQl5xsCnG837rAEhBZh?p=preview

What you want to do then is to listen for a click on the page, and if the click is outside of the calendar, then close it, otherwise do nothing. The above only takes into account that you are clicking on something that has a class name which includes datepicker-calendar, you will need to adjust it so that clicking within the calendar doesn't close it as well.