Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <nav>
- <span id="section_1">
- Secção 1
- </span>
- <span id="section_2">
- Secção 2
- </span>
- <span id="section_3">
- Secção 3
- </span>
- <span id="section_4">
- Secção 4
- </span>
- </nav>
- <div class="section" data-section="section_1">
- </div>
- <div class="section" data-section="section_2">
- </div>
- <div class="section" data-section="section_3">
- </div>
- <div class="section" data-section="section_4">
- </div>
- $('span').on('click', function() {
- $('span').removeClass('active');
- $(this).addClass('active');
- var spanId = $(this).prop('id');
- $("html, body").animate({
- scrollTop: $('div[data-section="' +spanId+ '"]').offset().top
- });
- });
- var alturas = [];
- var countSections = $('.section').length;
- for(var i = 0; i < countSections; i++) {
- alturas.push($('.section').eq(i).offset().top);
- }
- console.log(alturas);
- $(window).on('scroll', function() {
- countAlturas = alturas.length;
- scrollTopPx = $(window).scrollTop();
- for(var i = 0; i < countAlturas; i++) {
- if(scrollTopPx >= (alturas[i])) {
- $('span').removeClass('active');
- $('span').eq(i).addClass('active');
- }
- }
- });
- (function ($) {
- //Add current view's highlighting to the navigation
- /** helper for highlighting */
- function highlightNav(navLinks,id)
- {
- navLinks.filter('[href="/#'+id+'"]').addClass("active");
- }
- $(window).scroll(function() {
- //console.log("They see me scrollin, they hatin");
- //clear highlighting
- var navLinks = $('.site-navigation a');
- navLinks.removeClass("active");
- //calc current viewport
- var viewTop = $(window).scrollTop();
- var viewBottom = viewTop + $(window).height();
- //for all h1 and h2 elements, check if they are visible
- //performance tweak: stop each() after the first element is found to be behind view
- var previous = "";
- var foundOne = false;
- var fallback = "";
- $('h1, h2').each(function(i,e) {
- //get element position;
- var eTop = $(e).offset().top;
- var eBottom = eTop + $(e).height();
- var id=e.id;
- id = id.replace("_title", "");
- if (eTop >= viewTop) {
- //if we are passed the view and no heading was highlighted yet, store previous one as fallback
- if (! foundOne) {
- fallback=previous;
- }
- if (eBottom <= viewBottom) {
- highlightNav(navLinks, id);
- foundOne = true;
- } else {
- return false; //break the each(), the rest is below
- }
- }
- previous=id;
- });
- //no h1/h2 is in the viewport, so highlight the last one above
- if (! foundOne) {
- highlightNav(navLinks, fallback);
- }
- });
- })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement