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

Sam Buck
Sam Buck
8,087 Points

How can I use jquery to add a div once the screen reaches a maximum or minimum size?

I have a page built with a sidebar. However, once the screen gets too small, it is impractical to have a sidebar taking up so much space. I solved this by having it slide off screen.

I would like to add a div above the rest of the page content that includes the same content originally held by my sidebar.

I'm assuming that there is a way to trigger the jquery .add() function with screen size...any help would be greatly appreciated!

Instead of having it slide of screen why not just have it drop below the main content using a CSS media query?

1 Answer

What about this if you really wanted to use JS instead of CSS?

var add = true;
$(window).resize(function () {
    if (window.innerWidth < 300 /* or some other width */ && add) {
        add = false;
        $("element").add("element");
    } else if (window.innerWidth >= 300) {
        add = true;
    }
});
Sam Buck
Sam Buck
8,087 Points

That looks like it could work!