Forgive me if this is a very basic question, but I’m hoping someone here can explain it very clearly for a beginner to JS.
I noticed that I’ve used the same code in two places and therefore made a function to fire. But I want to use a variable that I created in this function to use after it’s been completed. Here’s a code example:
function calculate_animation(direction) {
var theWidth = parseInt(visibleArea.outerWidth() - 70),
currentMargin = parseInt(listingsSlider.css('margin-left')),
hoursVisible = Math.floor(theWidth / itemWidth),
hoursWidth = itemWidth * hoursVisible,
newMargin = currentMargin - hoursWidth;
}
forwardBtn.click(function () {
calculate_animation();
// animate the slider
listingsSlider.animate({
'margin-left': newMargin + 'px'
});
});
So I created a new variable called newMargin in the calculate_animation function, and I’m trying to use it in the animate function below.
What do I need to do to make this happen?
It is a scope issue. The newMargin variable is defined inside the function and so the scope of the variable begins at the beginning of the function where it defined with
varkeyword and ends at the end of the function.You can use
return newMarginto return the calculated value back to the caller.See below,