How to simplify scroll to section and back to top actions

0

I have the soft scrolling functions of the menu 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, could you unify in a single action?

    
asked by anonymous 15.11.2017 / 22:55

1 answer

0

I was able 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>

Now 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;
}
    
16.11.2017 / 14:33