Skip to content
Related Articles

Related Articles

Improve Article

Difference between window.onkeypress and window.document.body.onkeypress

  • Last Updated : 18 Jan, 2021

The onkeypress event can be triggered in JavaScript using both:

  1. window.onkeypress
  2. 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.

HTML DOM

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 filewindow.document.body refers to the body tag

3

The window is supporting IE4 and above whiledocument.body supports IE6 and above

 Conclusion: Though they produce similar output their functionality in terms of selecting the object is different.




My Personal Notes arrow_drop_up
Recommended Articles
Page :