Bronzato
Bronzato

Reputation: 9362

Displaying elements on my page depending on the page width

I would like to adjust elements displayed on my view depending on the width of the page. Let's say the page width is greater than 800 px, then I would like to display div A + div B (see picture below).

enter image description here

But if the page width is less or equal than 600 px,then I would like to display only div A.

enter image description here

It has to be dynamic. So If the user resize the window, the div B must be showed or hided.

A jQuery solution?

Thanks.

Upvotes: 0

Views: 151

Answers (3)

Eric
Eric

Reputation: 97681

Do it in CSS, using media queries!

@media screen and (max-width: 799px) { 
    #b {
        display:none;
    }
}

jsfiddle

Upvotes: 3

Rahul Sekhar
Rahul Sekhar

Reputation: 2851

Assuming you'd like non-javascript users to see both A and B:

$(document).ready(function() {

    var $divB = $('....'); // Define div B here using selectors

    $(window).resize(function() {
        if ($(window).width() < 800) {
            $divB.hide();
        }
        else {
            $divB.show();
        }
    });
});

EDIT: Whoops, didn't see that you wanted it to be dynamic. Changed.

Doing it in CSS as Eric says is a better option than jQuery, though.

Upvotes: 1

Kae Verens
Kae Verens

Reputation: 4077

$(function(){
  var $body=$(document.body), width=$body.outerWidth(), c='large';
  if (width<600) {
    c='small';
  }
  else if (width<800) {
    c='medium';
  }
  $body.addClass(c);
});

then use body.small, body.medium and body.large in your CSS to provide different layouts.

Upvotes: 1

Related Questions