Juraj Garaj
Juraj Garaj

Reputation: 113

jQuery - set calculated div width

I tried to set on my page posts as cards to one div with id="content" (like on G+).

#content {
    margin-top: 120px;
    margin-bottom: 70px;
    margin-left: auto ;
    margin-right: auto ;
    height: auto;
}
.card {
    height: 250px;
    width: 500px;
    margin: 10px;
    float: left;

}

and I want to calculate how much .card I can fit into the screen. So I tried this:

$(document).ready(function () {
    "use strict"; 
    var cardAmount = (Math.floor($(window).width/520))*520;
    $("#content").css("width", cardAmount);

});

but the problem is(I think) the second parameter of .css must by string and it's not.

Upvotes: 2

Views: 285

Answers (2)

Vijay
Vijay

Reputation: 418

I guess you are missing the syntax with the px or % in the css .

$("#content").css("width", cardAmount+"%");#or
$("#content").css("width", cardAmount+"px");#or
$("#content").css("width", cardAmount+"em");

Upvotes: 0

wap300
wap300

Reputation: 2770

The problem is most likely that you need to add a unit to this number so the CSS engine knows what to do with it.

Also, there's another problem with your code - your not calling width function here: $(window).width. Please remember that width is a function from jQuery API, not DOM API parameter that you can simply get like this. So the whole fix is quite simple:

var cardAmount = Math.floor($(window).width() / 520);
$("#content").css("width", cardAmount + "px");

Here - see how it works in this fiddle

Upvotes: 4

Related Questions