Cory Loudenback Cory Loudenback - 4 months ago 12
CSS Question

Modifying CSS position with JS

I'm using document.getElementById("").style.top = var; to randomly change the position of an object every time I click on it, but I can only randomly change the position by pixels and not percentage. How do I randomly generate a number with % ?

document.getElementById("randObject").onclick = function () {

var bColor = "#"+((1<<24)*Math.random()|0).toString(16);
var yAxis = Math.random()*100;
var xAxis = Math.random()*100;

document.getElementById("randObject").style.backgroundColor = bColor;
document.getElementById("randObject").style.top = yAxis;
document.getElementById("randObject").style.left = xAxis;
}

Answer
document.getElementById("randObject").style.top = yAxis + "%";
document.getElementById("randObject").style.left = xAxis + "%";

I should point out that your color generator is also not valid 1/16 of the time. You need to left-zero-pad the string:

"#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);

Another shortcut you can use to save DOM lookup time is to use the this keyword in your click event. All together it looks like:

Lastly, you might consider using .addEventListener('click', function() { ... }) since that is the current standard, though what you're doing works alright if you reeeally want to support IE6.

Let's check out the demo since this looks like a pretty neat script now:

document.getElementById("randObject").addEventListener('click', function() {
  var bColor = "#" + ("00000" + ((1<<24) * Math.random() | 0).toString(16)).slice(-6);
  var yAxis = Math.random() * 100;
  var xAxis = Math.random() * 100;

  this.style.backgroundColor = bColor;
  this.style.top = yAxis + "%";
  this.style.left = xAxis + "%";
});
:root {
  /* change this value to update the size of playing field and #randObject */
  --size: 50px;
}

html {
  position: absolute;
  margin: 0 var(--size) var(--size) 0;
  padding: 0;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

body {
  margin: 0;
  padding: 0;
}

#randObject {
  position: absolute;
  top: 0;
  left: 0;
  width: var(--size);
  height: var(--size);
  background-color: #000000;
  border-radius: 50%;
  cursor: pointer;
  transition-property: top, left, background-color;
  transition-duration: 0.4s;
}
<div id="randObject"></div>

Comments