jQuery scroll remove function after one use

61 Views Asked by At

I have a masthead that,on page load sits at the bottom of the viewport. On hover it scrolls to the top.

   $('.home #masthead').hover(function(){
    $("body").scrollTo($(this), 1000);
});

What I'd like to do is only allow this behaviour once as it causes unexpected effects as the user mouses and scrolls the page.

How to I unbind this function after it is used once?

Edit: I should probably explain the only reason I need this functionality is that there's a dropdown menu within #masthead cropped by the viewport base and I think it's more elegant if I move the masthead to the top when the user is interested. It may, however, been bad UX in either case. Although it does reveal the next section rather nicely (and it happens before the user has time to get to the menu)

3

There are 3 best solutions below

3
Renato Niola On

One option is that you could remove the #masthead class when the scrolling is done, if the #masthead is necessary for other purposes then you could add another class and remove that instead.

1
sina farbod On

you can use a global variable flag like:

var hasUsed = false
if(hasUsed === false){
  $('.home #masthead').hover(function(){
    hasUsed = true
    $("body").scrollTo($(this), 1000);
  });
}
0
Chris Pink On

Building on @Renato Niola's answer with @Shikkedial's observation, we get

 $('.home #masthead.virgin').hover(function(){
      if ($(this).hasClass('virgin')) {
          $("body").scrollTo($(this), 1000);
          $(this).removeClass('virgin');
      }
});