aiddev
aiddev

Reputation: 1429

scroll is wrong while one section is showing on scroll

here is my DEMO

jQuery(document).ready(function () {
    $('ul.subMenu li a').click(function () {
        jQuery('ul.subMenu li a.curM').removeClass('curM');
        jQuery(this).addClass('curM');

        var target = $(this).attr('href');

        var getHeaderHeight = jQuery(".header_wrap").height();
        $('html, body').stop().animate({
            'scrollTop': $(target).offset().top - getHeaderHeight - (getHeaderHeight*!$(".header_wrap").hasClass("fixed_nav_menu"))
        }, 'fast', 'swing');


    });

    jQuery(window).scroll(function () {
        jQuery('.header_wrap').addClass('fixed_nav_menu');
        if (jQuery(document).scrollTop() == 0) {
            jQuery('.header_wrap').removeClass('fixed_nav_menu');
        }
        jQuery(".hidden_section").fadeIn(1500);

    });

});

Section named 'Third Section' in demo is showing during scroll, and because of this when you click on each section which is after it, for example 'Affiliations' you will see that it doesn't scroll to corresponding section for now to 'Affiliations' section. But second time when you click on menu items everything is good, it scrolls to the corresponding section.

How can I solve this, so everytime when you click on menu items fading section won't prevent to scroll corresponding section?

Upvotes: 0

Views: 109

Answers (1)

dreamweiver
dreamweiver

Reputation: 6002

Issue In your approach :

  • Your trying to show(fade-in effect) the third-section div after the navigation(eg.publication section) is completed,which is why third-section is shown at the top of the screen instead of publication section.

What have i done :

  • The scroll event on the window is triggered after the Navigation is completed, so the logic to show the div in fade-in effect is added inside scroll event handler.

  • Offset top position of the target element third-section is checked against the current view-port position, based on that third-section is shown with fade-in effect to the user when scrolled or when navigated


JS CODE:

 $(window).scroll(function () {
    $('.header_wrap').addClass('fixed_nav_menu');
    if ($(document).scrollTop() === 0) {
        $('.header_wrap').removeClass('fixed_nav_menu');
    }

    var top_of_object = $(".hidden_section").offset().top;
    var bottom_of_window = $(window).scrollTop() + $(window).height();

    /* If the object is completely visible in the window, fade it it */
    if (bottom_of_window > top_of_object) {
        $('.hidden_section').animate({
            'opacity': '1'
        }, 1500);
    }
});

CSS:

.hidden_section {
  /*display:none;*/
  opacity:0
}

Note: Dont use Jquery & $ both in your code, try one of the notation in your entire code base else your code will look too confusing to read.

Live Demo @ JSFiddle

Upvotes: 1

Related Questions