Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS jQuery Basics (2014) Creating a Mobile Drop Down Menu Perform: Part 3

Kevin Phillips
Kevin Phillips
15,693 Points

Might this be obtrusive CSS we're introducing?

Suppose JavaScript bits don't load in the page. Then by using the media query in CSS we prevent the user from seeing the navigation on mobile devices!

I think a better approach would be to use some if/else magic on $(window).width()<cutOffWidth and throwing in an event listener of the form $(window).resize(myResponsiveJSFn).

Anyone care to weigh in on the philosophy of Andrew's CSS approach versus a pure JavaScript approach?

Is there a chance JavaScript won't be available but CSS will?

3 Answers

Matthew Panton
Matthew Panton
15,228 Points

It's much more likely that JavaScript will not be available that CSS. Using a $(window).resize() function is not really ideal because you then have to calculate the dimensions of the page each time it resizes (Note: you can't simply use $(window).width() ) because it will return a different value depending on the browser. Also If the function has to re-run each time the page is resized, this can make the page go all laggy and not good. I'd stick to using media queries but if you really wanted to use javascript, make sure you implement a debounce function to prevent the script from running more times than the browser can cope with.

Hop this helped :)

Kevin Phillips
Kevin Phillips
15,693 Points

Thanks Mathew!

What makes a media query faster than the JavaScript analog? Is the media query only run once and the result cached until needed?

Matthew Panton
Matthew Panton
15,228 Points

Hi Kevin,

I don't know the complexities of how it all works but from experience I know media queries just work better.

Marko Paasila
Marko Paasila
6,313 Points

Can we add some css to the html or css file with jQuery? In that case the #menu li items would dissappear only if the .js file is loaded, and else be visible.