I'm facing a challenging question that I can't seem to figure out on my own.
At the top of my page, I have some anchors that smoothly scroll down to different articles:
I would like to indicate to visitors their location on the page by rotating an arrow. This arrow should point towards the article it represents. In the image below, you can see the desired implementation where as the user scrolls past anchor 1 (an article with dynamic height) and moves on to read anchor 2:
If the visitor is not within the article but the next anchor 3 article is still visible below the scrolled position, it should display as shown below:
However, this poses a couple of challenges for me:
- Is there a way to write a jQuery script that allows dynamically adding anchors?
- How can I incorporate a rotation animation without using an additional library? (Currently utilizing jquery.transit)
Current code snippet: (obtained from another post: jsfiddle.net/m2zQE)
var topRange = 200, // measure from the top of the viewport to X pixels down
edgeMargin = 20, // margin above the top or margin from the end of the page
animationTime = 1200, // time in milliseconds
contentTop = [];
$(document).ready(function(){
// Stop animated scroll if the user does something
$('html,body').bind('scroll mousedown DOMMouseScroll mousewheel keyup', function(e){
if ( e.which > 0 || e.type == 'mousedown' || e.type == 'mousewheel' ){
$('html,body').stop();
}
})
// Set up content an array of locations
$('#navTopBar').find('a').each(function(){
contentTop.push( $( $(this).attr('href') ).offset().top );
})
// Animate menu scroll to content
$('#navTopBar').find('a').click(function(){
var sel = this,
newTop = Math.min( contentTop[ $('#navTopBar a').index( $(this) ) ], $(document).height() - $(window).height() ); // get content top or top position if at the document bottom
$('html,body').stop().animate({ 'scrollTop' : newTop }, animationTime, function(){
window.location.hash = $(sel).attr('href');
});
return false;
})
// rotate arrow
$(window).scroll(function(){
var winTop = $(window).scrollTop(),
bodyHt = $(document).height(),
vpHt = $(window).height() + edgeMargin; // viewport height + margin
$.each( contentTop, function(i,loc){
if ( ( loc > winTop - edgeMargin && ( loc < winTop + topRange || ( winTop + vpHt ) >= bodyHt ) ) ){
$('#navTopBar .anchor img')
.removeClass('open')
.eq(i).addClass('open');
}
})
})
})
Thank you in advance for your help!