0

So I have this function to prevent the body scrolling when the sidebar is hovered. The problem is, I can't get the mouseout function to work properly.

var currentScroll=0;
function lockscroll(){
    $(window).scrollTop(currentScroll);
}


$(document).ready(function (){

        $(".sidebarholder, .commentswrapper").hover(function (){
            currentScroll=$(window).scrollTop();
            $(window).bind('scroll',lockscroll);

        })  



})

My question is, how do I unbind it on the mouseout?

If I do this, it just stops working altogether.

    $(".sidebarholder, .commentswrapper").mouseout(function(){
        currentScroll=$(window).scrollTop();
        $(window).unbind('scroll');

    })
andy
  • 2,746
  • 7
  • 47
  • 63

2 Answers2

3

jQuery's hover() has built in "hover off", which might be helpful:

   $(".sidebarholder, .commentswrapper").hover(
     function (){ // hover over
       currentScroll=$(window).scrollTop();
       $(window).bind('scroll',lockscroll);
     },
     function (){ // hover off
       currentScroll=$(window).scrollTop();
       $(window).unbind('scroll',lockscroll);
     }
   )

http://api.jquery.com/hover/

showdev
  • 28,454
  • 37
  • 55
  • 73
  • This works, but it breaks infinite scrolling as well after you hover off, I can't think why? – andy Apr 19 '13 at 22:04
  • I'm guessing that's because of `unbind('scroll')`, but I'm not sure. Your infinite scrolling may also be bound to 'scroll'. Maybe try: `$(window).unbind('scroll',lockscroll);` instead. – showdev Apr 19 '13 at 22:08
  • shouldn't unbinding it effectively reset it? – andy Apr 19 '13 at 22:10
  • You are unbinding anything bound to the 'scroll' event. If infinite scroll is bound to the 'scroll' event, it gets unbound, too. I think you can unbind one specific handler from an event. Here's an example: http://stackoverflow.com/questions/3972886/how-to-unbind-a-specific-event-handler#3972922 – showdev Apr 19 '13 at 22:11
  • You're awesome showdev, $(window).unbind('scroll',lockscroll); seems to unbind the specific handler and makes infinite scroll work properly after the hover off. – andy Apr 19 '13 at 22:12
  • Sweet! Glad to hear it works. I edited my answer to include the `unbind` specifics. – showdev Apr 19 '13 at 22:13
0

Have you tried

     $(document).ready(function () {
        $(".sidebarholder, .commentswrapper").hover(function () {
           currentScroll = $(window).scrollTop();
           $(window).bind('scroll', lockscroll);

        }, function () {
           currentScroll = $(window).scrollTop();
           $(window).unbind('scroll');

        })
     })
Ejaz
  • 8,719
  • 3
  • 34
  • 49