Saving HREF value after clicking a link

therefore, I am a little new to JavaScript / jQuery, and I try to gradually implement it on my website (www.joeyorlando.me).

The current problem I'm trying to deal with is that my site slowly scrolls down to the desired section when the user clicks on one of the links at the top of the page (i.e. the user clicks on the "background") and the page scrolls slowly to the "background"). Ideally, I would even like the scroll function to slightly go past the top of the section (maybe 50-100 pixels), and then smoothly “bounce” back to the beginning of the section.

My idea was to save the HREF value from the clicked link, and then use that href value so that the page scrolls down to this section. I focus only on the first part, storing the HREF value for the link, and this is what I have so far, but it does not work properly, the console keeps telling me that HREF is not defined when I try to check the value from HREF after Clicking one of the links.

HTML code

<nav>
  <ul>
    <li><a href="#about">About</a></li>
    <li><a href="#background">Background</a></li>
    <li><a href="#research">Research</a></li>
    <li><a href="#travels">Travels</a></li>
    <li><a href="#contact">Contact Me</a></li>
  </ul>
</nav>
<body>
  <div id="about"></div>
  <div id="background"></div>
  <div id="research"></div>
  <div id="travels"></div>
  <div id="contact"></div>

JavaScript code

 $('nav ul li a').click(function() {
     window.location.href =  $(this).attr('href');
    var href =  $(this).attr('href');
 });

In addition, brownie points to anyone who can give me advice on making the page scroll slowly down to the right place. I tried using .scrollTo () but it did not work properly for me :(

Thanks in advance guys!

+4
source share
2

href?

:

$(document).ready(function() {
    $('ul li a').click(function() {
        var id = $(this).attr('href');
        $('html, body').animate({
            scrollTop : $(id).offset().top
        }, 500);
    });
});

: http://jsfiddle.net/fd7U7/

+1

LorDex, :

$(document).ready(function() {
    var body = $('html, body');
    $('ul li a').click(function() {
        var id = $(this).attr('href');
        var elem = $(id);
        var direction = elem.offset().top > $(document).scrollTop() ? 1 : -1;
        body.animate({
            scrollTop : elem.offset().top + (50 * direction)
        }, 500).promise().then(function() { 
            body.animate({
                scrollTop: elem.offset().top
            }, 500)
        });

    });
});

http://jsfiddle.net/fd7U7/3/

, , .

0

All Articles