Fylix
Fylix

Reputation: 2713

Differences between window.onkeypress vs window.document.body.onkeypress

I inherited this JavaScript code which reads in the input key event and process them, however I am getting duplicate for each key pressed.

Intelisense shows "window" as

var window: Window & typeof globalThis

    this.listen = function() {

       //when comment one of these two out, my duplicate issue goes away.
       window.onkeypress = this.captureKeyPress;  
       window.document.body.onkeypress = this.captureKeyPress;
    }


    this.captureKeyPress = function(e) {
       //process key input event
    }

I researched around but I cannot seem to find the different between window.keypress and window.document.body.onkeypress. Some of the resource about key press event refers to GlobalEventHandlers.onkeypress or document.onkeypress.

Can someone point me to the document or resource talking about these two events and their differences? I have a feeling they implemented this way due to supporting legacy browser such as IE7 or IE9 and earlier.

Upvotes: 1

Views: 1333

Answers (3)

uranshishko
uranshishko

Reputation: 312

See What is the difference between document and window objects

The difference is that with window.onkeypress you are registering an event on the window object and with window.document.body.onkeypressyou are registering an event on the body. An event will trigger for a specific element when it is in focus. However an event registered to that elements parent element will also trigger, hence an event registered to the window will trigger either way, and so do the ones registered on the document or body.

See jsbin example

window.onkeypress = function() {
  console.log('key pressed window')
}

window.document.body.onkeypress = function() {
  console.log('key pressed body')
}

document.getElementById('div').onkeypress = function() {
  console.log('key pressed div');
}
<div id="div">
  <input type="text" />
</div>

Upvotes: 1

Saar Davidson
Saar Davidson

Reputation: 1382

The Document.body property represents the or node of the current document, or null if no such element exists.

A global variable, window, representing the window in which the script is running, is exposed to JavaScript code.

basically window.document.body refers to the body tag while window is all the file. as for supporting legacy browsers such as IE7 or IE9 and earlier - window is supporting IE4 and above while Document.body supports IE6 and above. either way IE7 and above is fine with the event.

sources

Document.body

window

Upvotes: 1

mplungjan
mplungjan

Reputation: 178109

They work the same in Chrome at least - one is on the window the other on the body

window.onkeypress = function(e) { console.log("okp",e.key) }
window.document.body.onkeypress = function(e) { console.log("dbokp",e.key) }

Upvotes: 1

Related Questions