user6571878
user6571878

Reputation:

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();
        });                 
    }
});

Upvotes: 0

Views: 83

Answers (3)

serraosays
serraosays

Reputation: 7859

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.

Upvotes: 2

Pat
Pat

Reputation: 2750

$(window).width() returns an int (screen width in pixels). In order to get that value in ems you need to divide that buy the body's font-size, then compare that with just '48' not '48em'. For example:

$(window).resize(function() {
    if(($(window).width() / parseFloat($("body").css("font-size"))) < 48) {
        //  Do stuff here...              
    }
});

Upvotes: 0

Stayko Dimitrov
Stayko Dimitrov

Reputation: 87

Your problem is that you're assigning a behavior on smaller resolution. You practically want to assign a click event only when the window size is smaller than 48 em.

With simple words - just remove the click event:

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

EDIT I agree with the guy above about the CSS. Those things basically should be done with media queries.

Upvotes: 0

Related Questions