Jquery ile “Sayfa başına dön” butonu yapmak

back-to-top

Jquery kütüphanesi kullanarak yapılan, içeriği çok uzun olan sayfalarda kullanıcıları tekrar sitenin en üstüne göndermek için kullanacağınız “Back to top” butonunu kullanmak için aşağıdaki kodlardan faydalanabilirsiniz.

HTML

<a href="#" id="back-to-top" title="Back to top">&uarr;</a>

CSS

#back-to-top {
    position: fixed;
    bottom: 40px;
    right: 40px;
    z-index: 9999;
    width: 32px;
    height: 32px;
    text-align: center;
    line-height: 30px;
    background: #f5f5f5;
    color: #444;
    cursor: pointer;
    border: 0;
    border-radius: 2px;
    text-decoration: none;
    transition: opacity 0.2s ease-out;
    opacity: 0;
}
#back-to-top:hover {
    background: #e9ebec;
}
#back-to-top.show {
    opacity: 1;
}

JS

if ($('#back-to-top').length) {
    var scrollTrigger = 100, // px
        backToTop = function () {
            var scrollTop = $(window).scrollTop();
            if (scrollTop > scrollTrigger) {
                $('#back-to-top').addClass('show');
            } else {
                $('#back-to-top').removeClass('show');
            }
        };
    backToTop();
    $(window).on('scroll', function () {
        backToTop();
    });
    $('#back-to-top').on('click', function (e) {
        e.preventDefault();
        $('html,body').animate({
            scrollTop: 0
        }, 700);
    });
}

 

Hakan Demirel

pcanalist.com kurucularından Hakan Demirel, özel bir şirkette Front-end Developer olarak çalışmakta. Twitter üzerinden @hakandemirel hesabını takip edebilir yada hakandemirel.com adresinden daha fazla bilgi alabilirsiniz.

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Yandex.Metrica