Gradients

by Jagrati Tomar

HTML

<div id="app">

</div>

CSS

/* #app {
  width: 400px;
  height: 100px;
  transition: width 0.5s ease;
} */

#app {
  width: 400px;
}

JavaScript

const appElm = document.getElementById('app');
const colors = ["red", "green", "blue", "orange", "pink"]

function getRandomInt(x) {
	return Math.floor(Math.random() * x);
}

function getRandomWidths(x) {
	let sum = 0;
  const widths = [];
  for (let i = 0; i < x; i++) {
  	let width;
  	if (i == 0) {
    	width = getRandomInt(100);
      sum += width;
    } else if(i == x-1) {
    	width = 100 - sum;
      sum += width;
    } else {
    	width = getRandomInt(100 - sum);
      sum += width;
    }
    widths.push(sum);
  }
  return widths;
}

function test(x) {
	const widths = getRandomWidths(x);
  let p = widths.reduce((acc, w, i) => {
  if(i === 0) {
  	acc += `${colors[i]} ${w}%, `;
  } else {
  	acc += `${colors[i]} ${widths[i-1]}% ${w}% , `;
  }
  	return acc;
  }, "linear-gradient(to right, ");
  
  p = p.slice(0, p.length - 2);
  p+= ')';
  console.log(p);
  appElm.style.background = p;
 }
setInterval(() => {
   test(4)
 }, 600)
test(4);



// same thing with gradient

appElm.style.height = "100px";


/*function getDivs(x) {
  const divs = [];
  for (var i = 0; i < x; i++) {
    const ele = document.createElement('div');
    ele.style.height = "100%";
    ele.style.display = "inline-block";
    divs.push(ele);
    appElm.appendChild(ele);
  }
  return divs;
}



function main(x) {
  const divs = getDivs(x);
  test(x, divs);
  //setInterval(() => test(x, divs), 600);
}

main(5);


function test(x, divs) {
  const widths = getWidths(x);
  divs.forEach((elm, index) => {
    elm.style.backgroundColor = colors[index];
    elm.style.width = `${widths[index]}%`;
  });
}

function getRandomInt(x) {
  return Math.floor(Math.random() * x)

}

function getWidths(x) {
  const widths = [];
  let sum = 0;
  let width = 0;
  for (var i = 0; i < x; i++) {
    if (i ==- 0) {
      width = getRandomInt(100);
      sum = width;
    } else if (i === x-1) {
      width = 100 - sum;
    } else {
      width = getRandomInt(100 - sum);
      sum += width;
    }
   ...