2

What I need to do is add one of three CSS styles to every instance of .project_content in my HTML, and the style needs to be picked at random for each instance.

The three styles are as follows:
float:left
float:right OR
margin:auto + width:x (where the width of .project_content is calculated and x is the calculated width)

Right now I have this:

<script type="text/javascript">
$(document).ready(function(){
    var floats         = ["right","left"];                
  var rand = Math.floor(Math.random()*floats.length);           
  $('.project_content').css("float", floats[rand]);
});​​​​​​​​​​​​​
</script>

All this script is doing for me is applying float:left or float:right to ALL instances of .project_content instead of choosing right or left for each instance.

How do I get my script to pick a random variable for each instance of project_content and how can I add the margin:auto + calculated width into the mix? Thanks so much.

1 Answer 1

7

You need to get a random style for each element in the set, instead of a single random value for the entire set. That can be done using .css( propertyName, function(index, value) ), since the function gets called for each matched element:

$('.project_content').css("float", function () {
  var rand = Math.floor(Math.random() * floats.length);
  return floats[rand];  
})​;

DEMO.

To add margin and width into the mix, you can no longer use css() (since you need to modify one of multiple properties), but you can do it using .each():

var styles = [ "left", "right", "margin" ];
$('.project_content').each(function () {
  var randomStyle = styles[Math.floor(Math.random() * floats.length)];
  if (randomStyle == "left" || randomStyle == "right") {
    $(this).css('float', randomStyle);
  } else { // margin
    $(this).css('margin', 'auto')
           .css('width', your_calculated_width);
  }
})​;
Sign up to request clarification or add additional context in comments.

1 Comment

A little side note on this solution. You can get attributes of the relevant DOM element like this: $('element').css({left:function(){return $(this).attr('original-x');});

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.