JarFile
JarFile

Reputation: 318

HTML Anchor link smooth scrolling

I am trying to make an anchor link where when you click on it scroll down to another element. I have tried doing so with the answers from a previous question: Smooth scrolling when clicking an anchor link Using this code from it

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

When I use this code with this HTML

<a id="des" href="#scroll">
<img name="scroll" id="scroll" src="whatever">

It does not smooth scroll, but instead instantly jump here. It does also not jump to the right place. It jumps under the image so that you cannot see the image.

What I am trying to do: I am trying to have it so when I click on this anchor element, it smooth scrolls to this image without cutting it out. What I mean by this is when I do it now It skips over the image.

Upvotes: 0

Views: 1251

Answers (1)

Darkrum
Darkrum

Reputation: 1373

This will do what you want. It is from someone here at StackOverFlow. I don't remember which user though.

$(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
        }, 800);
        return false;
      }
    }
  });
});

Edit: Also this is what i did if there is a fixed nav at the top. This will offset the amount for your nav.

In css

a.anchor {
         display: block;
         position: relative;
         top: -45px; //or what ever the set px amount you have set to your nav
         visibility: hidden;
}

And use this anchor tag right before your image tag

<a class="anchor" id="WhateverYourHerfIs"></a>

Upvotes: 3

Related Questions