Ed Evans
Ed Evans

Reputation: 178

How do I get the actual event keydown target of an element inside a polymer component?

The code to prevent backspace from navigating back usually takes something like this approach, where the window keydown event is blocked for backspace, except on a small set of known element types like Input, TextArea, and so on.

This doesn't quite work for elements inside polymer custom elements, because the keydown event target type is the type of the custom element, not the actual element that got the keydown. Each custom element's type is different. This makes blocking backspace by target element type untenable.

Is there a way to know the type of the actual element, within the polymer element, that got the keypress? Or is there a better way altogether?

Upvotes: 3

Views: 7057

Answers (3)

Newred
Newred

Reputation: 729

Get element from event: DIV, INPUT, TEXTAREA ...

e.target.nodeName

Upvotes: 1

Scott Miles
Scott Miles

Reputation: 11027

Whenever possible, it's good to try to engineer your project to avoid breaking encapsulation. This is the reason the event.target is adjusted when you cross shadow boundaries.

However, the event.path property is an escape-hatch that contains an array of all the elements that have seen the event and should allow you to solve this problem.

Upvotes: 3

Ed Evans
Ed Evans

Reputation: 178

One way is to dig down into the custom element's shadowdom (and it's shadowdom), to get the true active element. Something like this works on Chromium 36:

function getActiveElem(target) {    
  do {
    if (target.shadowRoot != null)  {      
      target = target.shadowRoot.activeElement;
    }
  } while(target.shadowRoot != null);
  return target;
}

window.addEventListener("keydown", function(e) {
  if (e.keyCode == 8) {     
    var preventKeyDown;

    var d = getActiveElem(e.target);  // Get the real active element

    switch (d.tagName.toUpperCase()) {
      case 'INPUT':
        // more smarts here
        preventKeyDown = false;
        break;         
      // case TEXTAREA, et al.
    }
    // e.preventDefault() if preventKeyDown        
  }
}

Upvotes: 0

Related Questions