Search code examples
javascriptjqueryhtmlbackground-colorcountdown

how to make divs appear at the location where user clicks?


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.


Solution

  • 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>