The onkeypress event can be triggered in JavaScript using both:
- window.onkeypress
- window.document.body.onkeypress
To understand the difference between the two we need to have a look at the HTML DOM (Document Object Model):
- DOM is a model that represents the HTML document as a tree structure.
- The tree structure has the root node as a Document object.
- Other nodes like HTML, HEAD, and BODY have a parent/child relationship with each other.
window.onkeypress: The window.onkeypress event is triggered when a key is pressed on the window object.
Syntax:
window.onkeypress = function(){myScript};
Approach:
- Using the available window object call window.onkeypress to execute a function.
- Define the function(in our case myScript()) that you need to execute.
Note: Here the selected object is the window object, i.e. the root node of DOM.
Example:
HTML
<!DOCTYPE html> < html > < body > < script > window.onkeypress = function() {myFunction()}; function myFunction() { alert("Hi"); } </ script > </ body > </ html > |
Output:
window.document.body.onkeypress: The window.document.body.onkeypress event is triggered when a key is pressed on the body object.
Syntax:
window.document.body.onkeypress = function(){myScript};
Approach:
- Using the available window object call window.onkeypress to execute a function.
- Define the function(in our case myScript()) that you need to execute.
Note: Here the selected object is the body object which is the child of the HTML node which is further the child of the window object, i.e. the root node of DOM.
Example:
HTML
<!DOCTYPE html> < html > < body > < script > window.document.body.onkeypress = function() {myFunction()}; function myFunction() { alert("Hi"); } </ script > </ body > </ html > |
Output:
Difference between the window.onkeypress and window.document.body.onkeypress:
S. No. |
window.onkeypress |
window.document.body.onkeypress |
1 |
The selected object is the window object, i.e. the root node of DOM. | The selected object is the body object which is the child of the HTML node which is further the child of window object, i.e. the root node of DOM. |
2 |
The window is all the file | window.document.body refers to the body tag |
3 |
The window is supporting IE4 and above while | document.body supports IE6 and above |
4. | The windows.onkeypress event occurs when the user presses a key on a keyboard. | The window.document.body.onkeypress event occurs when the user presses a key on body object. |
5. |
Its supported browsers are -: Chrome , Microsoft Edge, Safari, Opera Mini, firefox |
Its supported browsers are -: Chrome, Microsoft Edge, Safari, Opera Mini, firefox |
Conclusion: Though they produce similar output their functionality in terms of selecting the object is different.