2

I found this useful jQuery for a navigation that highlights as linked content scrolls. I think I understand how this works, however I'm having trouble including transitions / animations for clicked items. I want the sections to smoothly transition when triggered by the navigation.

I have tried adding this to the CSS

.section {
transition: transform .5s ease-in-out;
}

and also to jQuery

$('#navigation').click(function(){
$('.section').animate('slow');
});

I'd really appreciate an explanation of what I am doing wrong in this particular example.

Here is the code and https://jsfiddle.net/r040p7oa/

<div id="navigation">
<ul>
    <li><a href="#section1">Section 1</a></li>
    <li><a href="#section2">Section 2</a></li>     
</ul>
</div>
<div id="sections">
<div id ="section1" class="section">I'm section 1</div>
<div id ="section2" class="section">I'm section 2
</div>   

#sections {
position: absolute;
top: 0;
left: 120px;
}

#navigation {
position: fixed;
top: 0;
left: 0;
}

.active {
background: red;
}

.section {
padding-bottom: 400px;
}

-

$(window).scroll(function() {

var position = $(this).scrollTop();

$('.section').each(function() {
    var target = $(this).offset().top;
    var id = $(this).attr('id');

    if (position >= target) {
        $('#navigation > ul > li > a').removeClass('active');
        $('#navigation > ul > li > a[href=#' + id + ']').addClass('active');
    }
});
});

https://jsfiddle.net/r040p7oa/

Community
  • 1
  • 1
user3821345
  • 648
  • 1
  • 11
  • 33

2 Answers2

1
$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});

Working fiddle :) Code from here

Community
  • 1
  • 1
Samuel Hill
  • 176
  • 1
  • 13
  • Ah ha! Thanks so much, also for the link – user3821345 Jan 07 '16 at 14:25
  • using `e.preventDefault()` is best practice over `return false`. See [this post](http://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault) for in-depth explanation. – giorgio Jan 07 '16 at 14:28
  • Sure thing! Glad I could help. @giorgio good point, thank you. – Samuel Hill Jan 07 '16 at 14:34
  • @SamuelHill Sorry to ask like this, but would you know how I could change the offset to the top of the page, so that the links respond sooner? I'm trying everything! // .offset().top + 200 // .scrollTop({top:200}) but no luck – user3821345 Jan 10 '16 at 21:06
  • @user3821345 is [this](https://jsfiddle.net/r040p7oa/5/) kind of what you're going for? – Samuel Hill Jan 11 '16 at 15:50
  • @SamuelHill Ugh so simple! You are a champion for answering, thanks a lot – user3821345 Jan 11 '16 at 15:55
0

This should do it:

$('a').click(function(e) {
   e.preventDefault();
   $('body, html').animate({scrollTop:$($(this).attr("href")).offset().top});
  });

Here is the JSFiddle demo

Ahs N
  • 8,233
  • 1
  • 28
  • 33