user2228313
user2228313

Reputation: 119

Change CSS Class height and width in javascript depending on screen res

I want the size of a div class 'content' to change depending on the size of the users' screen resolution.

So far Ive written this javascript

function resize()
{

    if ((screen.width>1024)) { $(".content").style.width = 560 + "px"; $(".content").style.height = 315 + "px" }
    if ((screen.width>1280)) { $(".content").style.width = 640 + "px"; $(".content").style.height = 360 + "px" }
    else { $(".content").style.width = 853 + "px"; $(".content").style.height = 480 + "px" }
};

and obviously in the html I have the class '.content'

why is this code not working?

Upvotes: 5

Views: 38151

Answers (2)

Giovanni
Giovanni

Reputation: 580

You can try and just use jQuery and CSS

   function checkWindowSize() {  

    if ( $(window).width() > 1800 ) {  
        $('content').addClass('large');  
    }  
    else {  
        $('content').removeClass('large');  
    }  

}  

$(window).resize(checkWindowSize);  

For the CSS you would need to write it out like this:

#content{  

}  

.large #content{  

}  

Here is a tutorial Source

Upvotes: 2

jszobody
jszobody

Reputation: 28911

Your specific issue here is that you are mixing jQuery and raw javascript.

To set the width of an element with jQuery, use the width() or css() method:

$(".content").width(560);
$(".content").css('width',560);

Having said that, you may be better off looking at the browser size, not screen resolution. Shouldn't your content respond to the size of my browser, regardless of my screensize? I don't keep my browser fullscreen.

Lastly, look at css media queries even to respond to the browser size. There are much better ways of doing this.

Upvotes: 7

Related Questions