I am trying to make a fixed navigation that allows me to scroll through the elements on the page and count where you are on the page. I saw a couple of examples to which I changed a little, but could not get them to work properly. My last attempt works fine when you switch between previous / next buttons to go from section to section, but I want to consider where the user is on the page. For example, if I double-click the next button, the counter is 2, and it takes me to the second section of the page. Then, if you click the previous button once, the counter will be 1, and it will take my first section on the page. Now, if I scroll down to the middle of the page (using the browser scroll bar) and click the next button, the counter will be 3,and it will lead me to the second section on the page. I want him to move me to the next visible section on the page. I need a way to determine which section the user is in, and point it to my logic so that someone can easily navigate the page using either their scroll bar or this fixed navigation. How can I achieve this?
JS Fiddle: http://jsfiddle.net/picitelli/fCLKm/
Js
function scrollTo(el) {
$('html,body').animate({
scrollTop: $(el).offset().top
}, 500);
}
var scroller = $('.scroller'),
scrollNext = scroller.find('.next'),
scrollPrev = scroller.find('.prev'),
count = 0,
sectionCounter = $('.section').length;
scrollNext.on("click", function() {
if (count < sectionCounter && count !== sectionCounter) {
count++;
scrollTo('.section:eq(' + count + ')');
} else {
}
console.log(count);
});
scrollPrev.on("click", function() {
if (count > 0) {
count--;
scrollTo('.section:eq(' + count + ')');
} else {
}
console.log(count);
});
HTML
<div class="scroller">
<span class="prev">Previous</span>
<span class="next">Next</span>
</div>
<div class="content">Lorem ipsum some content...</div>
<div class="section">A</div>
<div class="section">B</div>
<div class="section">C</div>
<div class="section">D</div>
<div class="section">E</div>
<div class="section">F</div>
<div class="section">G</div>
<div class="section">H</div>
<div class="section">I</div>
<div class="section">J</div>
<div class="section">K</div>
CSS
.content {
padding: 20px;
}
.section {
background: #f2f2f2;
height: 400px;
padding: 20px;
}
.section:nth-child(even) {
background: #ccc;
}
.scroller {
position: fixed;
right: 20px;
top: 20px;
}
.scroller span {
background: #fff;
color: #666;
cursor: pointer;
display: block;
font-size: 14px;
padding: 5px;
text-align: center;
width: 50px;
}
.scroller span:hover {
color: #000;
}
.scroller span.prev {
margin-bottom: 2px;
}
Any feedback / direction is welcome.
source
share