2

I'm trying to create this piece of code in which an element is pushed into an array, displayed and get a style added which gives them a random hex color. I got the hex color and the pushing into the array partly done, but I can't seem to be able to add the style nor display the div… Here is my code so far:

JS

var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
var elements = []
var el = '<div class="element bg"></div>'

document.getElementById("addEl").onclick = () => {
    elements.push(el)
    //console.log(elements)

    for (i = 0; i < elements.length; i++) {

        console.log(elements[i])
        document.write(elements[i])
        //elements[i].style.backgroundColor = colorBg
    }

}

HTML

<div class="container">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>

CSS

html, body{
    height:80%;
}

.container{
    width:100%;
    height:100%;
}

.element{
    width:100px !important;
    height:100px;
}
1
  • don't use document.write. Instead, retrieve the parent element of where you want your elements to be displayed and then parent.innerHTML += el Commented Mar 17, 2017 at 21:28

4 Answers 4

2

Do not use document.write(). Instead, create HTML elements with document.createElement() and then append them to other elements.

You can also just set their color and append them once when you create the element. No need to do all that for ALL the elements every time you click the button.

If you want to randomize the color of every element on every button press, you could instead select all of the elements, iterate over them, and randomize their color that way.

document.getElementById("addEl").onclick = () => {
    var el = document.createElement("div");
    el.className = ["element bg"];
    var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
    el.style.backgroundColor = colorBg
    document.getElementById("container").append(el)

}
html, body{
    height:80%;
}

#container{
}

.element{
    width:100px !important;
    height:100px;
    margin:10px;
    border:1px solid black;
}
<div id="container">
</div>
<input type="button" value="Add Block" id="addEl"/>

Sign up to request clarification or add additional context in comments.

2 Comments

is there a particular reason the variables are locally scoped instead of globally?
@Miguel Always keep variables scoped to the "closest" level that they are needed. You can create, edit, and append your new elements all from within the event listener function. There is no reason at all that they should be global. Use global scope sparingly.
1

To give structure to the code it is nice to have each operation as a separate function. Random color string generation, new DOM element construction (without displaying it), main actions. This way it is easy to read the code: can start reading at any point and understand what the lines of code are doing, not necessary having to learn the whole code logic.

What's happening here. It starts with a button click, which fires a "click" event, that has function addEl() bound to it. addEl() would acquire a new DOM element from createEl(), place it inside container element and push the element to the elements array if its required for some other functionality not covered in the original question.

function getColor() {
  return '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}

function createEl(){
  var el = document.createElement("div");
  el.className = "element bg";
  el.style.backgroundColor = getColor();
  return el;
}

function addEl() {
  var el = createEl();
  container.appendChild(el);
  elements.push(el);
}
var container = document.getElementById("container");
var elements = [];

document
  .getElementById("addEl")
  .addEventListener('click', addEl)
;
html, body{
    height:80%;
}

#container{
    width:100%;
    height:100%;
}

.element{
    width:100px !important;
    height:100px;
    float:left;
}
<div id="container"></div>
<input type="button" value="Add Block" id="addEl"/>

3 Comments

Please add some explanation of why/how this code helps the OP. This will help provide an answer future viewers can learn from. See this Meta question and its answers for more information.
can the array be removed completly in this case?
@Miguel I thought it is the task to have elements in the array as well. So, yes, there is no need in the elements array.
0

You would create elements using DOM methods instead of using document.write(). It's usage is discouraged. The following will do what you are after:

document.getElementById("addEl").addEventListener('click', () => {
  	 let container = document.querySelector('.container');
     let el = document.createElement("div");
     el.className = 'element bg';
     el.innerText = 'foo';
     el.style.backgroundColor = getRandomColor();
     container.appendChild(el);
});

function getRandomColor() {
 return '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
html, body{
    height:80%;
}

.container{
    width:100%;
    height:100%;
}

.element{
    width:100px !important;
    height:100px;
}
<div class="container">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>

Comments

0

This can be simply done using jquery

    $(function () {
    var elements = []

var el = '<div class="element bg"></div>'
        $("#addEl").click(function () {
        
        var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
 var el =     $("<div />",
{
    class: "element bg",
    css: {
        width: "20px",
        height: "10px",
        backgroundColor: colorBg
    }
});
         elements.push(el)
        $("#mycontainer").append(el);
            
        });

    })
html, body{
    height:80%;
}

.container{
    width:100%;
    height:100%;
}

.element{
    width:100px !important;
    height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="mycontainer">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>

1 Comment

i am trying to refrain from using jQuery tho, and learning how to do stuff in plain JS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.