Anthony John Anthony John - 3 months ago 7
CSS Question

the proper syntax for a function return to change a div dimensions in Javascript

I'm trying to make the height and width of a div change when i click on it by using the return of a function, but i can't seem to figure out how to get the syntax to read correctly(ei. "400px"). Thanks in advance for any help!

document.getElementById("box").onclick = function() {
function color() {
var choice = ["red", "blue", "green", "yellow", "purple", "orange", "pink", "gray", "brown"];
var random = Math.random();
random = (11 * random) / 1.25;
random = Math.floor(random);
return choice[random];
}

function size() {
var dimensions = x + 'px';
var x = Math.random();
x = x * 1000;
x = Math.floor(x);
return dimensions;
}

clickedTime = Date.now();
reactionTime = (clickedTime - createdTime) / 1000;
document.getElementById("time").innerHTML = reactionTime;
this.style.display = "none";
this.style.background = color();
this.style.height = size();
this.style.height = size();
size();

boxReset();
}

boxReset();

Answer

Aside from a certain form of function declaration, code is processed in the order it appears.

function size() {
  // x is undefined at this point and mostly useless
  var x = Math.random();
  // x is useful now
  x = x * 1000;
  // x is more useful
  x = Math.floor(x);
  // x is super useful now!
  var dimensions = x + 'px';
  // dimensions is useful now, too
  return dimensions;
}