Simple “scroll to/down” effect using minimal markup and hash tags

喜欢而已 提交于 2019-12-05 06:58:55

This is the best way I have found to do it - it just uses the normal anchors but extends their functionality

$('a').click(function() {
    var elementClicked = $(this).attr("href");
    var destination = $(elementClicked).offset().top;
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-15}, 500);
});

Here is a live example

I used straight jquery to do this.

I had a link like so ->

<a href="1" class="scrolling">Go to 1</a>

then using jquery it would scroll down to a div with another anchor with id "1"

$("a.scrolling").click(function(e) {
    e.preventDefault();
    goToByScroll($(this).attr("href"));
});

function goToByScroll(id) {
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');                               
}                       

There's ScrollTo in Javascript. It's a window event. check it out here: https://developer.mozilla.org/en/DOM/window.scrollTo

I found this code over the internet while searching for a quick way to create this scroll to effect.

html code:

<a href="#services">Jump to services</a>
<div id="services"></div>

jQuery code:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});

});

This is the Code source.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!