0

I am trying to make a responsive nav. I am using some jquery but I don't know javascript very well. I would like the toggle to take place when the window is a certain width (e.g. 1050px) this is the script

function adaptMenu() {

    /*  toggle menu on resize */

    $('nav').each(function() {
        var $width = $(this).css('max-width');
        $width = $width.replace('px', '');
        if ($(this).parent().width() < $width * 1.05) {
            $(this).children('.nav-main-list').hide(0);
            $(this).children('.nav-toggled').show(0);
        } else {
            $(this).children('.nav-main-list').show(0);
            $(this).children('.nav-toggled').hide(0);
        }
    });

}
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95
  • 1
    You may be able to use [CSS media queries](https://developers.google.com/web/fundamentals/layouts/rwd-fundamentals/use-media-queries?hl=en) to achieve this without the use of javascript. – Vincent Ramdhanie Nov 10 '14 at 02:18
  • Unrelated: Is it a PHP influence to name variables starting with $? Or jQuery? – rnrneverdies Nov 10 '14 at 16:16

1 Answers1

0

You can solve this by fixing the given javascript, but javascript is inefficient to handle responsive design. CSS engine is written in c++ and works faster, and automatically when browser is resized.

Better use CSS media query

The following snippet does the same as your javascript but with pure CSS.

<style>
@media (max-width: 1049px) {
  nav .nav-main-list {
    display: none;  /* hide .nav-main-list when browser windows width < 1050px */
  }
  nav .nav-toggle {
    display: initial;  /* show */
  }
}
@media (min-width: 1050px) {
  nav .nav-main-list {
    display: initial;  /* show .nav-main-list when browser windows width > 1050px */
  }
  nav .nav-toggle {
    display: none;     /* hide */ 
  }
}    
</style>

EDIT: As @Roko commented, media query does not work in IE8 and earlier. If you need support that browser, this post may help.

Community
  • 1
  • 1
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95