Sliding effect on 'anchor' links

9

I have a OnePage page and the anchor links of the menus when they clicked they only " skip " for the section of screen below but I wanted them slid gently to the intended 'anchor' section.

I tried to put transition via CSS and I was not successful, I do not know if I can not do this via CSS, or if I'm putting the class with transition in the wrong place.

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav navbar-right">
        <li>
            <a href="#contact" style="transition: all .25s linear;">Contato</a>
        </li>
    </ul>
</div>
    
asked by anonymous 01.10.2015 / 19:21

2 answers

10

Unfortunately this can not be done using CSS, to achieve this desired effect you will have to use Javascript / jQuery.

Here's an example below of how you can do this using jQuery, and you also have a JSFIDDLE LIVE EXAMPLE .

Well, first for the jQuery code below to work, you need to implement the jQuery Library, before closing the </head> tag on your site ( if you have not already implemented it). For this you have to add the following line of code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

ThenyoucaninsertthejQuerycodethatwillhandlethesmoothscrollingeffectfortheanchorlink,whichcanalsobeimplementedshortlyafterthislineofcodeabove.Everythingtogetherwilllooklikethis:

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script>
var $doc = $('html, body');
$('a').click(function() {
    $doc.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});
</script>
  

Note: The above jQuery code was created by pointing to the <a> tag, but   the recommended would be to create a class specifies only to handle   with this, such as class="scrollSuave" and add this   class to the links that you want this effect to be applied, for example:

<a href="#contact" class="scrollSuave">Contato</a>
<a href="#about" class="scrollSuave">Contato</a>
etc ...
     

Of course, also make this change in the jQuery code by pointing it now at class="scrollSuave" in this line:

$('.scrollSuave').click(function() {
     

In this way we are only pointing this script to the links that we want the effect to apply and not to all <a> links.

     

Here's a link to an example: link

    
01.10.2015 / 20:55
2

I use jQuery

var top = $('#contato').offset.top();

$(window).animation({
    scrollTop: top, // Separa condições.
}, 300);
    
01.10.2015 / 20:55