Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Do it in CSS, using media queries!

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

jsfiddle

Solution 2:

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

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

Solution 3:

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.

Post a Comment for "Displaying Elements On My Page Depending On The Page Width"