Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .toggle() and Media Queries

I'm using .toggle() on a button element:

$("header button").click(function(event){
    $(".site-nav-wrapper").toggle();
    event.preventDefault();
});

This works great. The problem is if the button is toggled to display:none and then I change the device orientation, triggering my desktop media query, despite the fact I re-force display:block; on the desktop media query, the button remains toggled to display:none:

(Sass):

.site-nav-wrapper{

            //Mobile First
            display:none;

            @include breakpoint($breakpoint-lg) {
                display:block;
            }
}

Is there a way to reset whatever the toggle() function is storing?

like image 814
Yahreen Avatar asked Aug 21 '12 02:08

Yahreen


2 Answers

toggle uses inline styling, which overrides whatever you're doing in your stylesheet.

To get the desired result, you should use a special hidden class to hide the element, and use toggleClass instead.

SASS:

.site-nav-wrapper.hidden {

    display: none;

    @include breakpoint($breakpoint-lg) {
        display: block;
    }
}

JS:

$("header button").click(function(event){
    $(".site-nav-wrapper").toggleClass('hidden');
    event.preventDefault();
});
like image 99
Joseph Silber Avatar answered Oct 22 '22 20:10

Joseph Silber


If I remember correctly toggle sets the display property to none on the element's style attribute. If you want to force the button to display in the "desktop" orientation then you'll need to include an !important declaration in your desktop breakpoint.

Alternately, you can listen for onorientationchanged and switch to the desktop version of the site then (un-toggling / activating everything that needs to be activated).

like image 32
Sean Vieira Avatar answered Oct 22 '22 19:10

Sean Vieira