0

I have a div on my page which I want to scroll up to after clicking a link in my navigation bar.

I wrote the following JavaScript for that, but it is not working.

<script>
    var currentpos = 0;
    function movedown(element){
        window.scrollBy(0,element.offsetHeight);
        delay = window.setInterval('movedown();',100);
        currentpos+=1;
        if(currentpos == element.offsetheight){
            stopscroll();
        }
    }
    function stopscroll(){
         window.clearInterval(delay);
    }
</script>
Marc Uberstein
  • 12,501
  • 3
  • 44
  • 72

1 Answers1

0

HTML

As noted in @andrewlorente's comment, if you just want it to jump to an element on the page, you can use an anchor link.

<a href="#targetElement">See more</a>

Downside is that it doesn't scroll - it jumps. It can be forced to scroll with JS though. This is a nice method to allow users to easily bookmark to certain parts on a page though.


JQUERY

If you're willing to use jQuery, this is a function that I use quite a bit to achieve the scrolling that you want.

It uses jQuery's ScrollTop method passing that into the animate() method. The last parameter of animate() is easing. You can pass in different strings to get different effects. You can view some of the different easing options.

/*
 * A scrollTo function that gets passed an ID & an optional offset
 *
 * @param {string}  location ('#resultsTop')
 * @param {integer} offset   (-100)
 */
function scrollTo(location, offset) {
    $("html, body").animate({scrollTop: ($(location).offset().top + (offset || 0) )}, "slow");
    return false;
};
EnigmaRM
  • 7,523
  • 11
  • 46
  • 72