1

I'd like to use jquery to manually write the css width of a series of element with a certain div class.

I'm trying to ask for the document width, record it as a variable, and then pass that variable to a new css 'width' rule...but my jquery skills are a little too meager

http://jsfiddle.net/ZEcCw/

Any ideas?

5 Answers 5

2

You're currently setting the width as the string literal "fiftypercent" - you meant the variable fiftypercent. Also, your selector needs to be a string.

$('.block').css("width", fiftypercent);​

What you had would have caused errors; with JavaScript, it always pays to look in the error console if something appears not to be working.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

var documentWidth = $(document).width();
var fiftypercent = documentWidth /2;
$(".block").each( function() { $(this).css("width",fiftypercent + "px") });

This would give all elemets with class ".block" the desired width. Maybe you should considder this:

$(".block").each( function() { $(this).css("width","50%") });

3 Comments

the first option works perfectly. I was trying to get around using %'s for some other reasons...
BUT I'm applying this class to an image and then sliding it down. since the width is fixed and the height is not, the image gets stretched. Is it possible to get each element to resize its height porportionally to the original image?
@user962642: there are many proposals to this problem, depending on the circumstances. Have a look at this site: techpp.com/2008/08/02/… it might be, a the way for you to go.
1

You messed up your quotes:

var documentWidth = $(document).width();
var fiftypercent = documentWidth /2;
$(".block").css("width", fiftypercent);

Note that i added quotes around the selector (.block) and removed quotes around fiftypercent to reference the variable.

1 Comment

This works until I add the next part of the code... AM I just missing another jquery language thing?jsfiddle.net/ZEcCw/28
0

Try doing this

var documentWidth = $(document).width();
var fiftypercent = documentWidth /2;
$('.block').css("width",fiftypercent)​​​​​​​​​​

Comments

0

You have used quotation marks in wrong places. If you want to change the size of the div when user resize the window you can try the following:

$(window).resize(function(){
  var doc = $(document).width();
  $(".block").css("width", (doc / 2) );  
}).resize()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.