skip to Main Content

I’m trying to make a button that, when clicked, creates a bunch of div elements, each containing the word, "hello". My code is here:

var start = function() {
  for (var i = 0; i < 16; i++) {
    var x = document.createElement('div');
    x.setAttribute('class', 'e');
    var t = 40;
    x.style.marginLeft = t + "px";
    var p = document.createElement('p');
    p.innerHTML = "hello";
    x.appendChild(p);
    document.body.append(x);
  }
};
.e {
  background-color: red;
  width: 5%;
  float: left;
  margin-top: 90px;
}

;
#start_button {
  float: left;
}
<button type="button" id="start_button" onclick="start()">Start</button>

Currently, when the button is clicked, the divs appear, but the button moves to the right, and I cannot find a way to keep it to the left. I tried setting the margin-left and margin-right to fixed values, but it doesn’t change it. What do i do? thanks in advance.

2

Answers


  1. Remove the semicolon after the class selector’s css where the } ends before the id selector. The semicolon there is syntactically wrong and creating abnormal behaviours.

    Login or Signup to reply.
  2. set the css for the button to:

        position: absolute;
        left: 30px;
        top: 20px;
    

    This will keep it at that place no matter what

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search