1

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.

4 Answers 4

1

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/

1

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

1
  • @CodeYoda, is this useful? Commented Apr 27, 2016 at 4:22
0

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

3
  • out of curiosity, if he is going to name the function what is the benefit of using one() rather than just off() once the condition is met?
    – Trey
    Commented Apr 26, 2016 at 18:06
  • @Trey That's a good question. Perhaps you have something there.
    – George
    Commented Apr 26, 2016 at 18:08
  • 1
    I wasn't aware of the one() method. Very helpful thanks! Commented Apr 27, 2016 at 14:39
0

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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.