0

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.

Community
  • 1
  • 1
JarFile
  • 318
  • 2
  • 8
  • 30

1 Answers1

3

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>
Darkrum
  • 1,325
  • 1
  • 10
  • 27
  • Yes, this smooth scrolls but still skips over the image. Should I make head for the divider element, or put text above the image? – JarFile Apr 16 '15 at 01:27
  • You should put the image in a div and have it anchor to the div instead of the image also do you have have a fixed nav bar at the top? with a set px height? – Darkrum Apr 16 '15 at 01:30
  • Ohh, I see the problem, yes I do have a fixed navbar at the top with set pix height n stuff. That is probably blocking the view. So it is going to the image but that is blocking it out. Where should I send the scrolling to go to then? Above the image a few pixels? – JarFile Apr 16 '15 at 01:34
  • One more question, how would I remove the #scroll from the url bar when it scrolls? – JarFile Apr 16 '15 at 01:50
  • The jQuery code i posted should do it. Reload your domain with out the # – Darkrum Apr 16 '15 at 01:52