0

If I'm in a textarea, I can do something like:

    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault()      return
    }

it detects within the textarea, but I want it to bubble up to some parent element. How can I do that?

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • It does bubble up unless you're specifically preventing it to do so. If you're having problems receiving the event in a parent element, you'll have to show a [mcve]. – Guy Incognito Jun 20 '20 at 13:42

2 Answers2

1

You can just put an onKeyPress on a div parent element as long as the textarea is the grand child and you are not doing the event.stopPropagation()

<div onkeypress="keyPress(event)">
<textarea>sample text area</textarea>
</div>

<script>
function keyPress(event) {
  alert(event.keyCode);
}
</script>
doppelgunner
  • 707
  • 6
  • 10
1

An event bubbles by default unless you use e.stopPropagation():

document.getElementsByTagName('textarea')[0].addEventListener('keyup', function(e) {
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault();
      return;
    }
});

document.getElementsByTagName('div')[0].addEventListener('keyup', function(e) {
    console.log('Bubbled');
});
<div>
  <textarea>
  </textarea>
</div>

Now if I understand you correctly, you want to prevent the default behavior on the element which has fired the event, but not on the parent elements.

In your particular use case, I guess you want to preserve the scroll behavior of the up and down arrows, but I'm afraid it's not possible for two reasons:

So you have to implement a scroll behavior yourself (which will result in a strange behavior for most users, in my opinion).

Guerric P
  • 30,447
  • 6
  • 48
  • 86