Captain_Planet
Captain_Planet

Reputation: 1336

How can I hide menu responsively after using jQuery toggle()?

I've created a simple responsive menu - here is a slim version: JsFiddle Here

HTML

<a href="javascript:void(0);" onclick="toggleNav()">
<span class="ico"><i class="fa fa-bars hvr-icon"></i></span> Dashboard
</a><ul id="submenu">
<li>Example Menu</li>
<li>Example Menu 2</li>
<li>Example Menu 3</li>
</ul>

JavaScript

function toggleNav() {
    $("#submenu").toggle();
}

CSS

#submenu {
  display:none;
}

I use jQuery to toggle() the display.

If I toggle the submenu to display, I would like to hide it again responsively (Eg without clicking the toggle button) when the screen size increases using a media query such as:

@media screen and (max-width: 991px) {

However, any CSS styles are overridden by the inline styles that toggle() writes.

Can anybody suggest a way of achieving this?

Thanks.

Upvotes: 2

Views: 63

Answers (2)

Umutambyi Gad
Umutambyi Gad

Reputation: 4101

you can simply use the JavaScript matchMedia to achieve that just see the following

Example

$(function(){
  var win_size = window.matchMedia( "(max-width: 320px)" );
  if (win_size.matches) {
    $("#submenu").addClass();
  } else{
    $("#submenu").removeClass();
  }
});

Upvotes: 2

imvain2
imvain2

Reputation: 15847

Instead of using toggle you can always use toggleClass instead. By toggling a class, that will allow you to add that class into various media queries, and style as you see fit.

.active{dispaly:block;}

function toggleNav() {
    $("#submenu").toggleClass("active");
}

@media screen and (max-width: 991px) {
   #submenu.active{
      display:none !important;
   }
}

You may or may not need the !important

Upvotes: 3

Related Questions