Search code examples
javascriptjquerydomgetelementsbytagnameonscroll

Selecting a HTML tag wih JS before the specific tag has been closed


I'd like to understand why I can't seem to be able to attach the onscroll to the variable containing the DOM element .

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="height: 1000px"></div>
<script>
  $(document).ready(function() {
    var vbody = document.getElementsByTagName('body');
    vbody.onscroll = function() {
      console.log('scrolling');
    }
  });
</script>
</body>
</html>

This code logs nothing. However, if you just change the

vbody.onscroll

to

window.onscroll

console logs "scrolling" when you, well, scroll - just like it should.

What am I doing wrong? I'd like add an onscroll event handler to the body element and have it function like when using window.onscroll in the example.

Thank you.


Solution

  • The following code gives you a HTMLCollection.

    document.getElementsByTagName('body');
    

    You need to use:

    $(document).ready(function() {
      var vbody = document.getElementsByTagName('body')[0];
      vbody.onscroll = function() {
        console.log('scrolling');
      }
    });
    

    Or since you are using jQuery, stick with it:

    $(document).ready(function() {
      $("body").scroll(function() {
        console.log('scrolling');
      });
    });