Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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.


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.