Search code examples
javascripthtmlcssmedia-queriesnav

How can I force to load a class that is only shown with the effect of JQuery in my Mediaquery?


I have an effect on my navigation whereas the navigition switches out after scrolling through the first window (height: 100vh;/or 500px in the fiddle). But the first nav is only interactable' on a mouse hover, which doesn't work for mobile users or people on tablets; I just want to make the second nav display on let's say widths below 900px; and kinda remove the first nav.

The second nav is only shown from Jquery/JS. With an if else statement; (if the window scrolls below 100vh height/500px in the fiddle, a class called full, which is the second nav) is added to the nav.

if ($window.scrollTop() > navShiftBreakpoint) {
            $navContainer.addClass( 'full' );}
     //full = the second nav & //navShiftBreakpoint = 500px

I made a Fiddle here, to visually explain the problem.

How can I fight this issue, any ideas?

Help and effort greatly appriciated!!


Solution

  • This technically does not answer your question - as you requested the layout change using a media-query, but I did figure out a jQuery/JS solution.

    If you check on load if the screen is less than 900px, and this is true, it will set the navbar to be like if you had scrolled already using the class you made. If this is not true, then it will call your original scroll function to change the layout after 500px.

    (function() {
    
    var $window = $( window ),
        $navContainer = $( '.nav-container' ),
            navShiftBreakpoint = 500; // px, when to change nav layout
    
    if ($(window).width() < 900) {
        $navContainer.addClass( 'full' );
    } else {
        $window.scroll(function() {
        if ($window.scrollTop() > navShiftBreakpoint) {
            $navContainer.addClass( 'full' );
                } else {
                $navContainer.removeClass( 'full' );
            };
            });
    }
    })(jQuery);
    

    EDIT: As per OP's request, here's an update to make sure that the layout 'updates' to the correct style when the screen size is changed, much like a standard media-query would do. This involved some resize events, but rather than explaining it, view the updated JSFiddle here.


    Feel free to ask any questions.