1

hello friends I have a link to an anchor in my html

<a href="#anchor">anchor</a>

And this goes to a div in my html

<div id="anchor" class="container-full">
</div>

My goals is to make it scroll a 100px lower, this is what I've tried with css but nothing happens, unfortunately.

#anchor{
    padding-top: -100px;
    margin-top: 100px;
}

EDIT added js

jQuery(".nav li a").click(function(e) {
        e.preventDefault();
        $id = jQuery(this).attr("data-id");
        jQuery("a.clicked").removeClass("clicked");
        jQuery(this).addClass("clicked");
        jQuery('html, body').animate({
           scrollTop: jQuery("#"+$id).offset().top
        }, 1000);
});
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
Frank Lucas
  • 582
  • 2
  • 12
  • 28

1 Answers1

0

Since you are already using jQuery to handle your scrolling, try adding 100 to your offset when setting your scrollTop property, which should cause your scrolling behavior to go 100px past the location of your target element in your animate() call :

jQuery('html, body').animate({
       scrollTop: jQuery("#"+$id).offset().top + 100 // scroll 100px past the element
}, 1000);

Example Snippet

.space { height: 500px; }
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <a href="#anchor" data-id='anchor'>anchor</a>
  <div class='space'></div>
  <div id="anchor" class="container-full"><h1>Hi</h1></div>
  <div class='space'></div>
  <script>
    $(function(){
      $("a").click(function(e) {
        e.preventDefault();
        $id = $(this).attr("data-id");
        $("a.clicked").removeClass("clicked");
        $(this).addClass("clicked");
        $('html, body').animate({
           scrollTop: $("#"+$id).offset().top + 100
        }, 1000);
      });
    });
    
  </script>
</body>
</html>
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • But I use this jQuery for other elements on the same page is there a way I can apply it only on a specific anchor? – Frank Lucas Apr 28 '16 at 06:59
  • You could just change the jQuery selector to be more specific such as using a selector like `#id` to only select a specific element by its `id` attribute. Or if you wanted to only target elements that had the `data-id` attribute, you could use `$('[data-id']).click(...)`. – Rion Williams Apr 28 '16 at 10:43