How to simplify scroll to Section and back to top actions

Asked

Viewed 73 times

0

I have the smooth scrolling menu functions for a One Page sessions as well as a smooth Back to Top:

var $doc = $('html, body');

$('a').not('#back-to-top').click(function (e) {
    e.preventDefault();
    $doc.animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

$(window).on('scroll', function () {
    if ($(window).scrollTop() > 100) {
        $('#back-to-top').addClass('show');
    } else {
        $('#back-to-top').removeClass('show');
    }
});

$('#back-to-top').on('click', function (e) {
    e.preventDefault();
    $doc.animate({
        scrollTop: 0
    }, 700);
});

css:

#back-to-top {
    position: fixed;
    bottom: 35px;
    right: 35px;
    z-index: 9999;
    width: 42px;
    height: 42px;
    text-align: center;
    line-height: 40px;
    background: #333;
    color: #fff;
    cursor: pointer;
    border: 1px solid #fff;
    border-radius: 2px;
    text-decoration: none;
    transition: opacity 0.2s ease-out;
    opacity: 0;
}
#back-to-top:hover {
    background: #000;
    opacity: 1 !important;
}
#back-to-top.show {
    opacity: 0.4;
}

How to simplify these actions, it would be possible to unify in a single action?

1 answer

0

I managed to solve my problem by producing the following result:

Back to top button (btn-scroll-top):

<a href="#" id="btn-scroll-top" class="back-to-top" title="Voltar ao topo">&uarr;</a>

To scroll to the anchor just create a link with the class scrollPage and an anchor. Example:

<!-- link -->
<a class="scrollPage" href="#contato">Contato</a>

<!-- ancora -->
<a id="contato"></a>

Javascript:

$('.scrollPage, .back-to-top').click(function (e) {
    e.preventDefault();

    $('html, body').animate({
        scrollTop: ($.attr(this, 'href') != '#') ? $($.attr(this, 'href')).offset().top : 0
    }, 500);
});

$(window).on('scroll', function () {
    if ($(window).scrollTop() > 100)
        $('#btn-scroll-top').addClass('show');
    else
        $('#btn-scroll-top').removeClass('show');
});

css:

#btn-scroll-top {
    position: fixed;
    bottom: 35px;
    right: 35px;
    width: 42px;
    height: 42px;
    text-align: center;
    line-height: 40px;
    background: #333;
    color: #fff;
    cursor: pointer;
    border: 1px solid #fff;
    border-radius: 5px;
    text-decoration: none;
    transition: opacity 0.5s ease-out;
    opacity: 0;
}

#btn-scroll-top:hover {
    background: #000;
    opacity: 1 !important;
}

#btn-scroll-top.show {
    opacity: 0.4;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.