Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading