Luke
Luke

Reputation: 990

How am I able to randomly set the position of the image in javascript

I am trying to make the smile.png image to appear in a random position within the specific <div>.

What I have done is to set the variable.style.top= top_position+'px' & variable.style.left = left_position+"px".

However, what I am getting so far are the images the are horizontally aligned and not randomly positioned. How am I able to do that?

var theLeftSide = document.getElementById("leftSide");
var randomY = Math.round(Math.random()) + 'px';
var randomX = Math.round(Math.random()) + 'px';

function generateFaces() {
  for (numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
    createElement(numberOfFaces);
  }
}

number = 0;

function createElement() {
  number++;
  //creating the image on the leftside
  var smiley = document.createElement('img');
  smiley.src = "smile.png";
  smiley.style.position = "absolute";
  smiley.style.left = randomX;
  smiley.style.top = randomY;
  theLeftSide.appendChild(smiley);
}
 #leftSide {
   position: absolute;
   width: 500px;
   height: 500px;
 }
 #rightSide {
   position: absolute;
   width: 500px;
   height: 500px;
   left: 500px;
   border-left: 1px solid black;
 }
<body id="smileyGuessingGame" onload="generateFaces()">
  <h1>Matching Game</h1>
  <p>Click on the extra smiling face on the left</p>
  <div id="leftSide">
  </div>
  <div id="rightSide">
  </div>


</body>

Upvotes: 0

Views: 1418

Answers (3)

I'd code this using jQuery and lodash. Here's a jsfiddle:

https://jsfiddle.net/mckinleymedia/3z6wsnyf/2/

The html:

<h1>Matching Game</h1>
<p>Find the unique image</p>
<div class="game"></div>

And the code:

var game = function(options) {
  var panes = 2,
    game = $('.game'),
    height = 500,
    width = game.width() / panes - 20,
    itemSize = 50,
    faces = 5,
    guesses = 5,
    setupBoard = function() {
      game
        .empty();
      _.times(panes, function(p) {
        game
          .append(
            $('<div>')
            .addClass('pane pane' + p)
            .css('height', height + 'px')
            .css('width', width + 'px')
          );
      })
    },
    startGame = function() {
      _.times(faces, function(i) {
        _.times(panes, function(p) {
          $('.pane' + p)
            .append(
              $('<img>')
              .attr('src', 'http://lorempixel.com/200/20' + i)
              .addClass('img-' + i)
              .css('top', _.random(height - itemSize) + 'px')
              .css('left', _.random(width - itemSize) + 'px')
            );
        })
      });
      $('.game img').click(function() {
        guesses--;
        alert('Nope!  You\'ve got ' + guesses + ' guesses remaining.');
      });
      $('.pane' + _.random(panes - 1))
        .append(
          $('<img>')
          .attr('src', 'http://lorempixel.com/200/20'+ (faces + 1))
          .addClass('img-t')
          .css('top', _.random(height - itemSize) + 'px')
          .css('left', _.random(width - itemSize) + 'px')
          .click(function() {
            alert('You got it! Good job!  You just cleared ' + faces + ' images!  You\'ve got ' + guesses + ' guesses remaining.');
            faces++;
            setupBoard();
            startGame();
          })
        );
      $('.game img')
        .css('height', itemSize + 'px')
        .css('width', itemSize + 'px')
        .css('-moz-border-radius', itemSize / 2 + 'px')
        .css('-webkit-border-radius', itemSize / 2 + 'px')
        .css('border-radius', itemSize / 2 + 'px')
        .css('-khtml-border-radius', itemSize / 2 + 'px')

    };
  setupBoard();
  startGame();
};
game();

Upvotes: 1

Rayon
Rayon

Reputation: 36609

There are few syntax errors in your code. You can compare your code with the code provided below.

Also note toFixed returns a A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place.

Try this:

var theLeftSide = document.getElementById("leftSide"),
  top_position = parseInt(Math.random() * ($(document).width() - 500)),
  left_position = parseInt(Math.random() * ($(document).width() - 500));

function generateFaces() {
  for (var numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
    createElement(numberOfFaces);
  }
}

var number = 0;

function createElement() {
  number++;
  //creating the image on the leftside
  var smiley = document.createElement('img');
  smiley.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Smiley_head_happy.svg/2000px-Smiley_head_happy.svg.png";
  smiley.style.position = 'absolute';
  smiley.style.top = top_position + "px";
  smiley.style.left = left_position + "px";
  theLeftSide.appendChild(smiley);
  top_position += 20;
  left_position += 20;
}
 #leftSide {
   position: absolute;
   width: 500px;
   height: 500px;
 }
 #rightSide {
   position: absolute;
   width: 500px;
   height: 500px;
   left: 500px;
   border-left: 1px solid black;
 }
 img {
   width: 100px;
   height: 100px;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body id="smileyGuessingGame" onload="generateFaces()">
  <h1>Matching Game</h1>
  <p>Click on the extra smiling face on the left</p>
  <div id="leftSide">
  </div>
  <div id="rightSide">
  </div>
</body>

Fiddle here

Upvotes: 1

salc2
salc2

Reputation: 577

Maybe something like this could work:

   function generateRandom(min, max) {
      var num = Math.random() * (max - min) + min;
      return Math.floor(num);
    }

    var width,
        height, 
        img;
    width = $( '#leftSide' ).width();
    height = $( '#leftSide' ).height();
    img = $('<img id="smiley">'); 
    img.attr('src', 'http://vignette2.wikia.nocookie.net/robocraft/images/2/26/Smile.png');
    img.css('top',generateRandom(0,height));
    img.css('left',generateRandom(0,width));
    img.appendTo('#leftSide');

demo: http://codepen.io/anon/pen/PZZrzz

Upvotes: 0

Related Questions