Goardo Goardo - 1 month ago 12
jQuery Question

Scroll to position conditional for tablet and mobile

I have the following first part working perfectly which scrolls to the top (allowing for a fixed navigation) and stops 155px from top of page. However as we come down to tablet the header drops to 75px depth and then to 65px on mobile.

Is there a way to conditionally scroll to a different position based on the css height of the nav bar? The commented out section is what I've been playing with.

$('a[href^="#"]').on('click', function(event) {

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

if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: (target.offset().top)-155
}, 1000);
}

// else if ( $(".dl-menuwrapper button").css("height") === "65px") {
// $('html, body').animate({
// scrollTop: (target.offset().top)-75
// }, 1000);
// }

});


Anybody have any ideas so I can get this working with an additional two heights for tablet and mobile?

Answer

I would get the height of the nav-bar as a variable, that way it doesn't matter what device is used.

$('a[href^="#"]').on('click', function(event) {
        var target = $( $(this).attr('href') ),
            navBarHeight = $(".nav").height();

        if( target.length ) {
            event.preventDefault();
            $('html, body').animate({
                scrollTop: (target.offset().top) - navBarHeight
            }, 1000);
        }

    });

Obviously, change $(".nav") to use the correct selector for your purpose. You could also add an offset by adding a constant to navBarHeight.

Comments