Search code examples
javascriptjquerynavbarsticky

JS: Is there a way to call a scroll function within a click function, or combine both?


My page has a sticky navbar whose 'stickiness' works fine, however the behaviour of the 2 main internal elements* of the navbar aren't seguing. The 2 main internal elements are the logo and the slide-out navbar(activated on click). The intended behaviour is as follows:

  • The logo(at center of orange bar) must 'hide' by default and only become visible when the user scrolls down 80px from the top (or scrolls upto 80px from the top) of the document.

  • The logo must hide as soon the user scrolls within 80px of the top of the document.

  • The logo must, however, never be visible at the same time the slide-out navbar is active.; the moment the navbar is inactive however, it must become visible again.

  • Unlike the logo, the navbar icon must always always be visible, and
    like the logo, it must be sticky.

In the jsfiddle, all of the intended behaviour plays out, but only on scroll, not on click. ie. After scrolling down more than 80px, the logo will be visible (which is fine), but does not hide when the navbar icon is clicked to the active state (unless the nav element was already in the active state). This issue is resolved the moment I scroll, but not at the moment of click which is what I want happening.

I know why this happening, it's because while I've taken care of all these conditions in $(window).scroll(function (), I haven't in the $("#menu-opener").click(function() simply because I couldn't use scrollTop() there, neither could I successfully combine the two functions.

How then, can I resolve this issue, whether through combining the functions, calling scrollTop() in the clickfunction, or anything else? Would appreciate any help.

Pls note: while I say '2 main internal elements of the navbar', in fact I've placed the logo and slide-out navbar in seperate divs and would like it to remain that way


Solution

  • So why couldn't you use scrollTop there ?

    isn't this the expected behaviour:

    https://jsfiddle.net/91gxLvbb/4/

    You can check the scrolltop with:

    if($(window).scrollTop() > 80)