0

I want to have a div filled with a background color and fixed dimensions ( width and height) appear on the screen wherever I click. However, if there are 10 div's on the screen, I want to stop being able to create a div when I click on the page and have a message (alert) tell me that "I'm done".

Thank you very much.

SimpleFuzz
  • 69
  • 9
  • 2
    Hey there, welcome to stack overflow. It will greatly increase the odds of getting a good answer if you can provide actual code showing what you've done so far. (It's hard to tell what you want from the question) – kthornbloom Jun 08 '16 at 18:50
  • Sounds pretty cool! Can't wait to see what you've tried so far. Please post your relevant code. – mferly Jun 08 '16 at 18:53

1 Answers1

4

See the example below.

var numOfDivs = 0;

document.addEventListener("click", function (e) {
  if (numOfDivs < 10) {
    var d = document.createElement("DIV");

    d.style.top = e.clientY + "px";
    d.style.left = e.clientX + "px";

    document.body.appendChild(d);

    numOfDivs++;
  } else {
      alert("Done");
  }
});
div {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
  transform: translateX(-50%) translateY(-50%);
}
<html>
<body>
</body>
</html>
Kian Cross
  • 1,818
  • 2
  • 21
  • 41
  • 1
    I would add a transform: translateX(-50%) translateY(-50%); to the elements css. Than you don't need the minus 25px and just have to set the top and left value. Makes it a bit easier mantainable and readable :) – user3528269 Jun 08 '16 at 19:01
  • @user3528269 Good idea :) I've added that. – Kian Cross Jun 08 '16 at 20:21