Search code examples
javascripthtmlfunctiongetboundingclientrect

Function not being executed. Scroll Event Listener


So, in my HTML I've got a class called .myFeature_info, along with that I've included the following script at the end of the <body> tag.

I'm wondering why the function is not being called while I am scrolling.

Here's the code, I'd love to know the 'why', I'd love to use JS only.

    window.addEventListener('scroll', function(e) {
    function isInViewPort (){
    var myFeature_info = document.getElementsByClassName('myFeature_info')[0];
    var getPos = myFeature_info.getBoundingClientRect();
    console.log(getPos);
  }
});

Solution

  • You are not calling any function on scroll but defining a function! Separate the definition and call it as you scroll:

    function isInViewPort (){
    var myFeature_info = document.getElementsByClassName('myFeature_info')[0];
    var getPos = myFeature_info.getBoundingClientRect();
    console.log(getPos);
    }
    
    window.addEventListener('scroll', function(e) {
     isInViewPort()
    }