In trying to learn JavaScript closures, I've confused myself a bit.
From what I've gathered over the web, a closure is...
Declaring a function within another function, and that inner function has access to its parent function's variables, even after that parent function has returned.
Here is a small sample of script from a recent project. It allows text in a div to be scrolled up and down by buttons.
var pageScroll = (function() {
var $page,
$next,
$prev,
canScroll = true,
textHeight,
scrollHeight;
var init = function() {
$page = $('#secondary-page');
// reset text
$page.scrollTop(0);
textHeight = $page.outerHeight();
scrollHeight = $page.attr('scrollHeight');
if (textHeight === scrollHeight) { // not enough text to scroll
return false;
};
$page.after('<div id="page-controls"><button id="page-prev">prev</button><button id="page-next">next</button></div>');
$next = $('#page-next');
$prev = $('#page-prev');
$prev.hide();
$next.click(scrollDown);
$prev.click(scrollUp);
};
var scrollDown = function() {
if ( ! canScroll) return;
canScroll = false;
var scrollTop = $page.scrollTop();
$prev.fadeIn(500);
if (scrollTop == textHeight) { // can we scroll any lower?
$next.fadeOut(500);
}
$page.animate({ scrollTop: '+=' + textHeight + 'px'}, 500, function() {
canScroll = true;
});
};
var scrollUp = function() {
$next.fadeIn(500);
$prev.fadeOut(500);
$page.animate({ scrollTop: 0}, 500);
};
$(document).ready(init);
}());
Does this example use closures? I know it has functions within functions, but is there a case where the outer variables being preserved is being used?
Am I using them without knowing it?
Thanks
Update
Would this make a closure if I placed this beneath the $(document).ready(init);
statement?
return {
scrollDown: scrollDown
};
Could it then be, if I wanted to make the text scroll down from anywhere else in JavaScript, I could do
pageScroll.scrollDown();
Another Update
Wow, looks like that worked! Here is the code on JSbin. Note the page scroller doesn't exactly work in this example (it doesn't seem to go to the bottom of the text), but that's OK :) Bonus points for anyone that can tell me why it's not scrolling to the bottom.