Search code examples
javascriptreturnvar

JavaScript return won't update new value


I am trying to determine the distance from the top of the page in JavaScript, and I am faced with a Problem that the return command won't update the new distance.

I tried to get the distance like this:

document.addEventListener('wheel', getDistance);
function getDistance() {
   var scrollTop     = $(window).scrollTop(),
        elementOffset = $('#distance-check').offset().top,
        distance      = (elementOffset - scrollTop);
        
        return distance;
}

var distance = getDistance();

But for some reason it will get only the initial distance value and wont update.

Thanks in advance.


Solution

  • Because the last line executes just once when the script is loaded. When the event listener fires, it calls the callback function but the return value is not used. Try

    
    let distance;
    
    document.addEventListener('wheel', getDistance);
    
    function getDistance() {
       var scrollTop     = $(window).scrollTop(),
            elementOffset = $('#distance-check').offset().top;
    
            distance = (elementOffset - scrollTop);
    }