0

I have two buttons. I use them to add/remove div's (class="rect") from the 'main' tag. I want to be able to change each of the divs' background color when clicking on it. I managed to do that for all the divs I'm creating at the first time the page loads but the function doesn't work on the new divs I add. I know it's because in my code the function is inside the onload but when i take it out it doesn't work. Any help please?

HTML:

<body>
    <div id="wrapper">
        <header>
        </header>

        <div id="buttonscontainer">
            <button class="button" id="add">+</button>  
            <button class="button" id="remove">-</button>   
        </div>
        <main id="main">
        </main>
    </div>

This is my last js attempt:

window.onload=function(){
    for(var i=0;i<6;i++){
            var rectangle = '<div class="rect"></div>';
            document.getElementById("main").innerHTML += rectangle;
        }
        document.getElementById("add").onclick = addRect;
        document.getElementById("remove").onclick = removeRect;
        var rectangles = document.getElementsByClassName('rect');
        for(var i = 0; i < rectangles.length; i++) {
            var rectangle = rectangles[i];
                rectangle.onclick = function() {
                    this.style.backgroundColor = "red";
                }
            }
    }


/*defines the behaviour of the addRect onclick*/
 function addRect(){
     var rectangle = '<div class="rect"></div>';
     document.getElementById("main").innerHTML += rectangle;
 }

 /*defines the behaviour of the removeRect onclick*/
 function removeRect(){
     var rectangle = '<div class="rect"></div>';
     document.getElementById("main").lastChild.remove();
 }
Max Meijer
  • 1,530
  • 1
  • 14
  • 23
Al.s
  • 300
  • 4
  • 20
  • You can add them to the onload method. – poxip Dec 18 '14 at 14:59
  • 1
    possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – hon2a Dec 18 '14 at 15:04
  • Actually the `addRect` function wipes out all the event listeners created within onload. `innerHTML += ...` doesn't append, it replaces. – Teemu Dec 18 '14 at 15:05
  • Have you tried using the "addEventListener" event? – Skywalker Dec 18 '14 at 15:05
  • 1
    @hon2a that question is using jQuery. This one isn't. – Max Meijer Dec 18 '14 at 15:08
  • You've assigned a function reference twice to an event listener, why can't you do the same third time? Currently you're creating an anonymous function for every `div`. What comes to use of `innerHTML`, please read, how to [create](https://developer.mozilla.org/en-US/docs/Web/API/document.createElement) and [append](https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild) elements. – Teemu Dec 18 '14 at 15:15
  • http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation – Benjamin Gruenbaum Dec 18 '14 at 15:27
  • @MaxMeijer You're right, but my recommendation would nevertheless be to look at that solution. Then, if OP doesn't want to use `jQuery`, he can have a look at `Node.addEventListener` and either manually attach listeners to newly created elements or create delegated binding using native JavaScript. – hon2a Dec 18 '14 at 15:28

2 Answers2

0

thanks for the replies...i finally solved it with the following changes:

window.onload=function(){
    for(var i=0;i<6;i++){
            var div = document.createElement("div");
            div.className = "rect";
            document.getElementById("main").appendChild(div);
        }
        document.getElementById("add").onclick = addRect;
        document.getElementById("remove").onclick = removeRect;
    }

window.onclick = function func(){var rectangles = document.getElementsByClassName('rect');
        for(var i = 0; i < rectangles.length; i++) {
            var rectangle = rectangles[i];
                rectangle.onclick = function() {
                    this.style.backgroundColor = "red";
                }
            }
    }
Al.s
  • 300
  • 4
  • 20
0

Please use event delegation

add one event listener to the parent Element holding the rects then use event.target to get the actual rectangle that was clicked

var rectHolder = document.getElementById('main');

rectHolder.addEventListener('click', function(event){
  var rectClicked = event.target;
  rectClicked.style.backgroundColor = 'red';
});
Edwin Reynoso
  • 1,511
  • 9
  • 18