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

JavaScript

Aashish Malik
Aashish Malik
10,675 Points

How do I trigger some jquery action based on screen width of the browsing window?TRIGGERING JQUERY BASED ON MEDIA QUERY?

I want to hide the menu(vertical) when the browser width is 520px or less. And replace it with a button called menu and toggle the menu by clicking on it.

2 Answers

Merritt Lawrenson
Merritt Lawrenson
13,477 Points

You can either trigger in javascript with the proper event or trigger in css with a media query, which I believe is how Chalkley does it in this series of Treehouse videos on how to create a mobile menu to replace a desktop-style one.

http://teamtreehouse.com/library/jquery-basics/creating-a-mobile-drop-down-menu/preparation

Rowan Weismiller
Rowan Weismiller
2,595 Points

You'd probably be interested in checking out the matchMedia window function.

if (window.matchMedia("(max-width: 520px)").matches) {
  // Code that runs at 520px and below to enable the mobile menu
} else {
  // Code that runs at 521px and above to disable the mobile menu
}

In addition, you can combine this with resize events to make sure the person browsing always sees what you intended, even if they resized it after load.

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

https://developer.mozilla.org/en-US/docs/Web/Events/resize