Ali Bahaari Ali Bahaari - 4 months ago 8
Javascript Question

How to run a jQuery Function in smaller width?

I want to do a something in a smaller width of screen But I have a problem. I'm creating a Responsive Navbar, So I want to show a Button when It is in small width & toggling the Menu. But when I hide the Menu in smaller width, It doesn't show the Menu in wider width Because of Hiding in jQuery ...

So I wanted to make jQuery Codes run JUST in smaller width, I wrote this But It doesn't work :

$(window).resize(function() {
if($(window).width() < '48em') {
$('.ji-toggle-btn').click(function() {
$(this).parent().find('ul').toggle();
});
}
});

Answer

The proper way to show/hide a button is with a media query in CSS:

.css example:

.ji-toggle-btn {
  display: none;
}    

@media (min-width: 48em) {
  .ji-toggle-btn {
    display: block;
  }
}

.scss example:

.ji-toggle-btn {
  display: none;

  @media (min-width: 48em) {
    display: block;
  }
}

I mocked up a sample of how to do a responsive sidebar: http://codepen.io/staypuftman/pen/dGOMYO

What you'll notice in this example is how little JS is used. Targeting a .toggle class and using css transitions will get you where you want to go. You're overthinking this approach with the JS.

Comments