Angus
Angus

Reputation: 449

One click multiple functions with arrays

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;
}

Upvotes: 2

Views: 63

Answers (4)

Serge
Serge

Reputation: 1601

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"/>

Upvotes: 1

radtelbi
radtelbi

Reputation: 635

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"/>

Upvotes: 0

jered
jered

Reputation: 11581

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"/>

Upvotes: 2

baao
baao

Reputation: 73241

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"/>

Upvotes: 0

Related Questions