Question

I am having an issue getting smooth scrolling to work within an overflowed element. The first link/anchor works as expected, but any subsequent links do not scroll to their anchor.

Fiddle: http://jsfiddle.net/BPyVd/1/

<!doctype html>
<html>
<head>

<style>
#container {width: 400px; height: 400px; background: #ccc; overflow-y: scroll}
div > div {margin-top: 500px; height: 1px; background: red;}
</style>
</head>

<body>
<div id="container">
    <a href="#anchor-a">NEXT</a>
    <div id="anchor-a"></div>
    <a href="#anchor-b">NEXT</a>
    <div id="anchor-b"></div>
    <a href="#anchor-c">NEXT</a>
    <div id="anchor-c"></div>
</div>

<script>
$(function() {
  $('a').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) {
        $('#container').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
</script>

</body>
</html>

Any help would be more than appreciated. Thank you.

Was it helpful?

Solution

Fixed Script :

<script>
$(function() {
  $('a').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) {
        $('#container').animate({
          scrollTop: $('#container').scrollTop() + target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top