3

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?

Community
  • 1
  • 1
Ed Evans
  • 178
  • 1
  • 7

3 Answers3

3

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.

Scott Miles
  • 11,025
  • 27
  • 32
  • [Event paths](http://www.w3.org/TR/shadow-dom/#event-paths) would be the best way to solve this problem, where we want to write a universal behavior at the top level. However, at least on Chromium 36.0.1985.97 (280598), the event.path is always zero length. – Ed Evans Sep 15 '14 at 13:16
  • Don't let the DevTools fool you. event.path being a zero length was a bug that was recently fixed: http://crbug.com/402749. – ebidel Sep 15 '14 at 16:21
1

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

e.target.nodeName
Newred
  • 699
  • 8
  • 8
0

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        
  }
}
Ed Evans
  • 178
  • 1
  • 7
  • This will fail on several paper elements which have more than one shadowRoot but wouldn't be too hard to support this too but Scotts solution is simpler anyway. – Günter Zöchbauer Sep 15 '14 at 06:42