Home > Software engineering >  JavaScript return won't update new value
JavaScript return won't update new value

Time:11-15

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.

CodePudding user response:

You do run the function each time the user scrolls, but you don't update the value :

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

let distance = getDistance();

// This is the important part
document.addEventListener('wheel', () => distance = getDistance());

CodePudding user response:

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);
}
  • Related