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

filipz
filipz
11,063 Points

Changing Javascript for different screen sizes?

I have javascript code that works well on desktop, but not on mobile. I would like to either use a different file for the mobile website or just 'turn off' the code that I currently have for javascript. How can I change javascript based on screen size?

Bryan Castleman
Bryan Castleman
9,520 Points

You can include a few lines of jQuery to do it. Here is an example:

Use a different width number if you like.

if ( $(window).width() > 739) {      
  //Add your javascript for large screens here 
} 
else {
  //Add your javascript for small screens here 
}

1 Answer

Steven Parker
Steven Parker
229,732 Points

You could add conditional code based on the width.

You could have an if...else code block that tests window.innerWidth for a value that would distinguish your displays.