0

how can one gently scroll to #name in a long html page ?

Example with codepen

I would like when I click on a link to scroll to a point in the page, how can I scroll gently ? using a transition feature - like ease-in ?

Clicking on "a" - to go to next page - but slowly. same as when I click on "b" it should go back up ease-in.

body {
  font-size: 20vh;
  text-align: center;
  vertical-align: middle;
  line-height: 20vh;
}

.aa {
  height: 100vh;
  background: #ccc
}

.bb {
  height: 100vh;
  background: #fdf
}

a {
  text-decoration: none;
  -webkit-animation: moveFromLeft .6s ease both;
  animation: moveFromLeft .6s ease both;
}

html a

<div class="bb">
  <a name="xx"></a>
  <a href="#yy">b</a>
</div>
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
hypermails
  • 726
  • 1
  • 10
  • 28
  • 6
    Check out this question: http://stackoverflow.com/questions/7717527/jquery-smooth-scrolling-when-clicking-an-anchor-link – DVCITIS Nov 24 '15 at 20:09
  • I did check stack and other locations and found several JS/Jquery solutions - but as title says, I am looking for a CSS solution. thanks – hypermails Nov 24 '15 at 20:43

3 Answers3

2

I'm not sure how to with css, however, a jQuery example would be:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

reference: Smooth Scrolling

VikingBlooded
  • 884
  • 1
  • 6
  • 17
0

You'll have to use a bit of jQuery. You can select any anchor tag that contains a hash character # and gently scroll to the desired content.

$("a[href*='#']").click(function() {
    var $href = $(this).attr("href");
    var $anchor = $($href).offset();
    $("html, body").animate({ scrollTop: $anchor.top }, 500);
    return false;
});

For example:

<a href="#secondDiv">Click Me</a>

would scroll to:

<div id="secondDiv"></div>

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
0

Use the :target pseudoclass in CSS3

See:> http://codepen.io/hrtzt/pen/NPZKRN#0

Tobias Schäfer
  • 1,330
  • 2
  • 17
  • 35