Why doesn't the jQuery script set the width of an element?
Question by JamesCharless
James here. I’m working on a site that I want to have the same number of posts no matter what the screen resolution. I’m trying to use this script, but it’s not working. It SHOULD get the width of the page document, subtract 400px, divide that number by 4, and then set the CSS of the element .entry to that math equation. Can anyone help me figure out what’s wrong? I’m new to jQuery, so it’s surprising I was able to even get this far.
EDIT: I solved my problem using this code in the end:
$(function() {
var cwidth = $(document).width() - 100;
var pwidth = cwidth - 150;
var ewidth = (pwidth - 150)/5;
$("#container").css("width", cwidth);
$("#posts").css("width", pwidth);
$(".entry").css("width", ewidth);
$(".photo").css("width", ewidth);
});
So thank you all quite a bit for helping. However, I’ve ran into a few more problems. For some reason even though the script divides by 5, there are only 4 posts per row and the posts overflow out of the div they’re in. Example: http://jamescharless.tumblr.com/ – I think this is because the div the entries are in doesn’t have a width set in the CSS since it’s added with jQuery. Does anyone know how to fix this? Also, I tried implementing masonry by David Desandro, and it just messes up the whole page. I think this is also because the div #posts and the div .entry doesn’t get a width via CSS. Can anyone help me with either of these issues?
Answer by Jack Franklin
You need to do:
$(document).width()
Not
$("document").width()
Working JSFiddle: http://jsfiddle.net/WsZry/
$(function() {
width = ($(document).width()-400)/4;
$(".entry").css("width", width);
});
As document
isn’t a HTML element, it’s a JavaScript property.
Answer by Starx
You quoted the document
inside double quotes $("document")
$(function() {
var width = ($(document).width() - 400)/4;
$(".entry").css("width", width);
});