febs
febs

Reputation: 145

Styling Divs with Javascript Vars

I'm doing a little experiment trying to randomly place images inside a div using a javascript loop. I've been having some trouble with it.

Here's what I have (simplified):

for(var i = 0; i < 10; i++)
{
var top = random(-20, 20);
var left = random(-20, 20);

document.write(
  <div class="one" style="\"left:" + left + ";\"">
    <img src="hein.png"/>
  </div>
);
}

The goal being to generate some top and left values, and every itteration display a new image with these generated values. I know it's a syntax error with the style="". But nothing I've tried has worked

How can I get this working.

Upvotes: 0

Views: 224

Answers (5)

febs
febs

Reputation: 145

Using PHP Instead:

<?php
// Middle coords of my div
    $top = 200;
    $left = 350;

    for($i = 0; $i < 20; $i += 1)
    {
        $tran = rand(-130,170);
        $lran = rand(-300,270);
        // Fix line breaks 
        $top = $top - 49;
        echo '<div style="position:relative;
                  display: block;
                  height: 49px;
                  width:49px;
                  left:' . ($left + $lran) . 'px;
                  top:' . ($top + $tran) . 'px;
               ">' . '<img src="img.png"/>' . '</div>';
    }

?>

Awesome! Thanks for the help with the string syntax!

Upvotes: 0

Guffa
Guffa

Reputation: 700650

You have forgotten to quote the string in the document.write call. Also you forgot the unit on the measurement.

for(var i = 0; i < 10; i++) {
   var top = random(-20, 20);
   var left = random(-20, 20);

   document.write(
      '<div class="one" style="left:' + left + 'px;top:' + top + 'px">' +
         '<img src="hein.png"/>' +
      '</div>'
   );
}

Upvotes: 0

Cristian Toma
Cristian Toma

Reputation: 5809

You should first consider using a JavaScript library like jQuery. This will simplify your work.

Let's say you have this markup

<div id="image-container">

</div>

Include jQuery in you markup

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>

From JavaScript you would do this, after you've included jQuery in your markup

for(var i = 0; i < 10; i++) {
    var top = random(-20, 20);
    var left = random(-20, 20);

    $('#image-container').append('<img src="hein.png" style="position: absolute; top: '+top+'; left : '+left +';" />');
}

Upvotes: 1

Eifion
Eifion

Reputation: 5553

You meed to wrap the whole of the document.write output in quotes, like this:

document.write('<div class="one" style="left:"' + left + ';"><img src="hein.png"/></div>');

Upvotes: 1

RaYell
RaYell

Reputation: 70434

You forgot the quotes in document.write and you are escaping wrong characters inside of it

document.write(
  "<div class=\"one\" style=\"left:" + left + ";\">
    <img src=\"hein.png\"/>
  </div>"
);

Upvotes: 0

Related Questions