Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect focusOut of entire component

Tags:

ember.js

I'm writing a suggestions component that basically will have the following functionality:

  • It has a text input
  • Once this text input gets focused it will show up a div under it with some info and links
  • This div has many p tags on it and some a tags.
  • When the focus goes out of the ENTIRE component it should hide the div

I've tried to write the focusOut event of my component like this:

focusOut: function(event, view){
  if (!$.contains(this.$('.autocomplete-group')[0], event.relatedTarget))
    this.set('showingSuggestions', false)
}

Basically it will see if the new focused item (event.relatedTarget) is inside the outer DIV of my component (wich has the autocomplete-group class).

This works fine on Chrome but not on Firefox nor IE. It turns out that FF does not fill the relatedTarget property.

Then I tried a solution that did not make e happy (cited here). It did not make me happy because hooking an event to the entire document doesn't seem right. Anyways it did not work as well.

My question is if there's a good, simple, cross browser way to simply detect if the focus went out of my entire component.

like image 431
Ricardo Acras Avatar asked Jan 12 '15 01:01

Ricardo Acras


1 Answers

Run the code in a new runloop using Em.run.later. Here is the sample of a code for one my addons. I am hiding a dropdown menu when focus goes out of the component.

lostFocus: function() {
    if(this.get('isOpen')) {
      Em.run.later(this, function() {
        var focussedElement = document.activeElement;
        var isFocussedOut = this.$().has(focussedElement).length === 0 
                && !this.$().is(focussedElement);

        if(isFocussedOut) {
          this.closeOptions({focus:false});
        }
      }, 0);
    }
  }.on('focusOut'),

Running the code in a separate runloop will ensure that you will get the document.activeElement correctly

like image 165
blessanm86 Avatar answered Sep 17 '22 18:09

blessanm86