sashomaga

Move html elements in circular path

Apr 14th, 2013
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Write a script that creates 5 div elements and moves them in circular path with interval of 100 milliseconds
  2.  
  3.      (function () {
  4.     'use strict';
  5.     var container = document.getElementById('container');
  6.         var documentFragment = document.createDocumentFragment();
  7.         var circleRadius = 150;
  8.         var centerX = 300;
  9.         var centerY = 300;
  10.         var divCount = 5;
  11.         var angleSizeInDegrees = 360 / divCount;
  12.         var angleInDegrees = angleSizeInDegrees;
  13.         var angleInRadians = angleInDegrees * Math.PI / 180.0;
  14.         var startingAnglesInDegrees = new Array(divCount);
  15.  
  16.         for (var index = 0; index < divCount; index++) {
  17.             var newDiv = document.createElement('div');
  18.  
  19.             newDiv.style.width = "50px";
  20.             newDiv.style.height = "50px";
  21.             newDiv.style.position = 'absolute';
  22.             startingAnglesInDegrees[index] = angleInDegrees;
  23.             newDiv.style.top = circleRadius * Math.cos(angleInRadians) + centerX + "px";
  24.             newDiv.style.left = circleRadius * Math.sin(angleInRadians) + centerY + "px";
  25.             newDiv.style.backgroundColor = "rgb(" + generateRandom(1, 255) + ", " +
  26.                         generateRandom(1, 255) + ", " + generateRandom(1, 255) + ")";
  27.             documentFragment.appendChild(newDiv);
  28.             angleInDegrees += angleSizeInDegrees;
  29.             angleInRadians = angleInDegrees * Math.PI / 180.0;
  30.         }
  31.  
  32.         container.appendChild(documentFragment);
  33.  
  34.         // lets move
  35.         var divSet = document.getElementsByTagName('div');
  36.         window.setInterval(moveDivs, 100);
  37.  
  38.         function moveDivs() {
  39.             for (var index = 0; index < divSet.length; index++) {
  40.  
  41.                 startingAnglesInDegrees[index]++;
  42.                 if (startingAnglesInDegrees[index] > 360) {
  43.                     startingAnglesInDegrees[index] = 0;
  44.                 }
  45.  
  46.                 angleInRadians = startingAnglesInDegrees[index] * Math.PI / 180.0;
  47.  
  48.                 divSet[index].style.top = (circleRadius * Math.cos(angleInRadians) + centerX) + "px";
  49.                 divSet[index].style.left = (circleRadius * Math.sin(angleInRadians) + centerY) + "px";
  50.             }
  51.         }
  52.  
  53.         function generateRandom(start, end) {
  54.             return Math.floor(Math.random() * (end - start) + start + 1);
  55.         }
  56.      })();
Advertisement
Add Comment
Please, Sign In to add comment