Ad

An Issue With JQuery And Safari

I am attempting to create a navigation bar that slides up and off the screen when a user scrolls down, and then scrolls back down when a user stops scrolling / scrolls up. Below is a snippet of my script and a jsfiddle:

$(document).ready(function() {

var position = $(window).scrollTop();
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        if (scroll > position) {
            $('.nav').addClass('active');
        } else {
            $('.nav').removeClass('active');
        }
        position = scroll;
    }); 
});

https://jsfiddle.net/z2uc89sL/

Coupled with my CSS this works fine in all the browsers I have tested it in except for Safari (I'm running version 9.0.2 on a Mac). The problem that is occurring is that when you hit the top of page and there is no further room to scroll up, the nav gets hidden again by re sliding up (as though the user was actually scrolling down again rather than butting up to the top of the page). The opposite is happening at the bottom of the page too.

If you look at the fiddle in Safari you will see the issue I am talking about. If you look at the fiddle in any other browser you'll see what I'm trying to achieve.

Ad

Answer

Below i tried to provide you two different answers, First solution is related to your .nav class while Second is simulation of same functionality as a function. So, it could be reused.

var el = $(".nav");
$(window).scroll(function() {
    el.addClass('active');
    clearTimeout($.data(this, "scrollCheck"));
    $.data(this, "scrollCheck", setTimeout(function() {
        el.removeClass('active');
    }, 250));
});

/*
 *  As a Function
 */
function scrollFunc(el) {
    var el = el;
    $(window).scroll(function() {
        el.addClass('active');
        clearTimeout($.data(this, "scrollCheck"));
        $.data(this, "scrollCheck", setTimeout(function() {
            el.removeClass('active');
        }, 250));
    });
}
scrollFunc($('nav'));

To see the results online, Please have a look at my fiddle https://jsfiddle.net/yeoman/g19nejfu/1/ i forked your question and update it with working answer.

I would love to explain about what's going on but actually this question is somehow answered already. So, for that purpose, i will share some useful links. One should check them out to understand it.

jQuery scroll() detect when user stops scrolling

http://gabrieleromanato.name/jquery-check-if-users-stop-scrolling/

Hope that my answer will you. Thanks, Cheers!

Ad
source: stackoverflow.com
Ad