Jim
Jim

Reputation: 1

Document keydown event propagates to a input child with stopPropagation

I have a problem with document event keydown. When i pressed on specifics keys (1 or 2), the event keydown propagates to input child. I used event.stopPropagate() but i doesn't work.

Here my code :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TEST KEYDOWN EVENT</title>
</head>
<body>
    <form>
        <label>Number of Series</label>
        <input type="number" name="nbSeries" value="10" id="nbSeries"/>
    </form>

    <script type="text/javascript">

        document.addEventListener('keydown', keyPressed);

        function keyPressed(e){

            e.stopPropagation();

            if(e.code == "Digit1" || e.code == "Digit2"){
                console.log('You pressed ' + e.code);
            }
        }
    </script>
</body>
</html>

On console, when i change my input (#nbSeries) value using key 1 and 2, display : You pressed "keyCode"...

Upvotes: 0

Views: 1968

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

stopPropagation only stops the event from propagating - stopping other listeners later from seeing the event. That does not stop the default behavior of the action. For example, it doesn't stop characters from appearing when typing into an input field. To achieve that, you need preventDefault instead.

document.addEventListener('keydown', keyPressed);
function keyPressed(e) {
  e.preventDefault();
  if (e.code == "Digit1" || e.code == "Digit2") {
    console.log('You pressed ' + e.code);
  }
}
<form>
  <label>Number of Series</label>
  <input type="number" name="nbSeries" value="10" id="nbSeries" />
</form>


Also, although it's not directly related to the problem you were experiencing, there's also something to keep in mind about how event propagation works. Listeners trigger in this order:

  • The topmost element (the window), capturing phase
  • The document, capturing phase
  • Ancestors of the target, capturing phase, descending towards the target, capturing phase
  • The target
  • Ancestors of the target, bubbling phase
  • ...

Since your document keydown listener is listening for bubbling events, it triggers only after the event's reached the target's listeners. If you were trying to have a listener on the document stop a listener on a child element from triggering, you would need to add the document listener in the capturing phase instead to prevent propagation downwards to the target, which can be done by passing true to addEventListener's third parameter.

Upvotes: 2

Related Questions