info343/lectures/more-events-creating-elements/files/rects.js

// rect.js
// JavaScript code for colored rectangles example, Lecture 7: More Events, Creating Elements
// INFO 343, Autumn 2012
// Morgan Doocy

// When the page is ready, create the rectangles and attack click handler to
// #color button.
$(document).ready(function() {
   // Create the rectangles.
   createRectangles();
   
   // Recolor all rectangles when #color button is clicked.
   $('#color').click(recolor);
});

// Create 50 rectangles, each at a random location within #rectanglearea.
function createRectangles() {
   for (var i = 0; i < 50; i++) {
      // Create a new div.rect
      var $rect = $('<div>', { 'class': 'rectangle' });
      
      // Generate random top & left coordinates.
      var top = Math.floor(Math.random() * 250);
      var left = Math.floor(Math.random() * 750);
      
      // Set those coordinates on the new rect.
      $rect.css('top', top +'px');
      $rect.css('left', left +'px');
      
      // Call the 'remove' function when this rect is clicked.
      $rect.click(remove);
      
      // Inject the new rect into #rectanglearea.
      $rect.appendTo('#rectanglearea');
   }
}

// Give each rectangle (except the example rectangle) a new random color.
function recolor() {
   // Iterate over all the rectangles *inside* #rectanglearea (excludes the example).
   $('#rectanglearea .rectangle').each(function() {
      // Generate random red, green, and blue values for a new color.
      var r = Math.floor(Math.random() * 255);
      var g = Math.floor(Math.random() * 255);
      var b = Math.floor(Math.random() * 255);
      
      // Set the current element's background color to our new random color.
      // Composes a CSS string like 'rgb(123, 45, 67)'.
      $(this).css('background-color', 'rgb(' + r + ', ' + g + ', ' + b + ')');
   });
}

// Remove this element from the page.
function remove() {
   $(this).remove();
}