I am trying to use this script to freeze scrolling when an 'lightbox-style' image is opened. There's probably just a small error in the script but can't figure it out
jQuery.fn.lockToggle = function () {
var top = $(window).scrollTop();
var left = $(window).scrollLeft();
var clickCount = 0;
$(this).click(function() {
clickCount++;
if(clickCount % 2 === 1 ){
$('body').css('overflow', 'hidden');
$(window).scroll(function(){
$(this).scrollTop(top).scrollLeft(left);
});
} else {
$('body').css('overflow', 'auto');
$(window).unbind('scroll');
}
});
return this;
};
How this script works (in display order):
- Grabs the current scroll position and stores it in two variables
- Creates a variable for the number of clicks the object has
- If the click count is odd then it freezes the page in its current position
- Else (is even) then it allows the page to be freely scrolled
All of this works in a simple jQuery function that can be used just by calling .lockToggle()
You can view this in a full example here:
http://jsfiddle.net/JamesKyle/8H7hR/30/
(Click on the image)