Ross Adriano
Ross Adriano

Reputation: 25

jQuery scroll to an element using .scroll(handler)

I am trying to scroll to a targeted element on my page after I've scrolled down a certain distance from the top of the page. So the scroll to the element is triggered by a .scroll() event. I have been able to do this using the following code:

$( document ).scroll( function( e ) {
    if ( $(document).scrollTop() > 250 ) {
        $('html, body').animate({
            scrollTop: $("#cy-hero-image").offset().top
        }, 650);
    }
});

However the problem is that once this event has been triggered by the scroll the page sticks to this scroll position. How can I write this code that it only jumps to this page position once when scrolled from the top of the page?

Here is the JSFiddle of what I have so far.

Upvotes: 1

Views: 84

Answers (4)

Rohit Goyani
Rohit Goyani

Reputation: 1256

Try it. It is working every-time while you visit top of the page.

var isScroll = true;
$(document).scroll(function(e) {
  if ($(document).scrollTop() > 250 && isScroll) {
    isScroll = false;
    $('html body').animate({
      scrollTop: $("#targeted-element").offset().top
    }, 650);
  }else if($(document).scrollTop() < 250){
    isScroll = true;
  }
});

JSFiddle

Upvotes: 1

Trey
Trey

Reputation: 5520

Just remove the scroll handler after it's used

var myScroll = function( e ) {
    if ( $(document).scrollTop() > 250) {
        $('html, body').animate({
            scrollTop: $("#cy-hero-image").offset().top
        }, 650);
        $(document).off(e);
    }
});
$(document).on('scroll', myScroll);

Upvotes: 0

Hugo S. Mendes
Hugo S. Mendes

Reputation: 1086

you can add a variable to check if it came from the top.

var startsFrom = 0;
$(document).scroll(function(e) {
  if($(document).scrollTop() == 0) //you can adjust it to match whatever you want
    startsFrom = 0;
  if ($(document).scrollTop() > 250 && startsFrom == 0) {
    startsFrom = $(document).scrollTop();
    $('html, body').animate({
      scrollTop: $("#targeted-element").offset().top
    }, 650);
  }
});

https://jsfiddle.net/pdyu3f5b/14/

Upvotes: 1

George
George

Reputation: 36794

Name your function and use .one() to attach your handler. Re-attach the handler if the break-point hasn't been met.

var myScrollFunc = function(e){
  if ($(document).scrollTop() > 250) {
    $('html, body').animate({
      scrollTop: $("#targeted-element").offset().top
    }, 650);
  } else {
    $(document).one('scroll', myScrollFunc);
  }
}

$(document).one('scroll', myScrollFunc);

JSFiddle

Upvotes: 0

Related Questions