0
// color pattern function
function colorPattern(color_Pattern_box)
{
    var color_Board = $("#colorBoard");
    var rtrnVal = ""; //default to standard syntax
    var color_temp = ("");

    for(var c = 0; c < color_Pattern_box.length; c++){
        var color_Split = color_Pattern_box[c].split(":");
        var color_Name = color_Split[0];
        var color_Value = color_Split[1];
        color_temp += "<div id="+color_Value+"; data-title="+color_Name+" onclick='' class='mycolor_warpper'; style='background: "+color_Value+";'></div>";
        var color_inset = $(".mycolor_warpper");
        colorpattern_attachEvent(color_inset, "click", updateNumberText, JsonSave);
    }

    // //input option to parent
    color_Board.html(color_temp);
}


function colorpattern_attachEvent(element, event, callbackFunction1, callbackFunction2) {
  if(typeof(element.addEventListener)=='function')  {
    element.addEventListener(event, function(){
      callbackFunction2(this.getAttribute("id"));
      callbackFunction1();
    }, false);
  }
}

I have function with loop, and I want to to use the loop to add eventListener to my class.

Basically, the loop will create div and class name "mycolor_wrapper". How do I attach each class with addEventListener() click, here is the code I tested it and it doesn't work.

zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • 1
    Looks like you have jQuery in your page, then why not use event delegation – Arun P Johny Apr 20 '16 at 03:29
  • 1
    It's overkill to add multiple eventListeners of the same eventType on identical elements. You can place the eventListener on the parent of a group of elements and save yourself some extra coding and it's efficient as well. – zer00ne Apr 20 '16 at 03:29
  • 1
    In side your for loop it's a mess ... You have a onclick attribute which is not handles correctly syntax wise.. Also you have. `var color_inset = $(".mycolor_warpper");` in the loop which will select all the existing elements with that class and not the one you are inserting now.and add event.. So what you end up with is multiple click events being blinded to elements.. Use event delegation.. To remove this pain.. – Rajshekar Reddy Apr 20 '16 at 03:32
  • yeah i know ,agree is a mess, i will remove that instant. thank for the advice. – Christopher Cheok Apr 20 '16 at 03:57

2 Answers2

1

i have function with loop, and I want to to use the loop to add eventlistener to my class.

There's an easier way to go about adding less and getting more, especially with jQuery as Dinglemeyer was explaining.

Basically the loop will create div and class name "mycolor_wrapper". How do I attach each class with addeventlistner click, here is the code i tested it won't work.

Ok, while clumping things together in a code lump might sound great, you should try coding for one portion of your code, test it and see if it works, then move on to the next. Like when you build a house you don't start on the roof and build the foundation then the frame.

So I'll answer this question:

…How do I attach each class with addeventlistner click…

generically with generic JavaScript.

First part of answer, as I have commented (and probably others have as well), you don't want to go that route. Adding multiple eventListeners of the same eventType is unnecessary and messy. Instead you can utilize the properties that will help you control the event bubbling:

  • event.target: The element that is clicked.

  • event.currentTarget: The element that you added an eventListener to. In a simple setup, this would be the same as the event.target. But in your situation it'll be different because we will add one eventListener to the parent element (i.e. #colorBoard) of multiple event.targets (i.e. .colorWrap(I hate underscores .colorWrap = .mycolor_warpper)).

  • event.stopPropagation(): This method will stop the propagation of the click event from bubbling up to the rest of the elements in the event chain (e.g. #colorBoard), thereby we will isolate the click event to just one element.

SNIPPET

// Reference the parent #colorBoard
var parent = document.getElementById('colorBoard');

// Add eventListener to parent
parent.addEventListener('click', trueColor, false);

// Create trueColor(event) eventHandler
function trueColor(event) {

  // If event.target is not event.currentTarget then...
  if (event.target !== event.currentTarget) {

    // Store event.target in the variable 'clicked'
    var clicked = event.target;

    // Next change clicked background-color to it's id.
    clicked.style.backgroundColor = clicked.id;

  }

  // Use event.stopPropagation() to prevent event bubbling so  #colorBoard will never hear the event.
  event.stopPropagation();
}
.colorBoard {
  border: 3px dashed black;
  width: 300px;
  height: 300px;
}
h1 {
  font-size: 20px;
  color: orange;
}
.colorWrap {
  height: 100px;
  width: 300px;
  cursor: pointer;
  font-size: 15px;
  color: white;
  background: black;
  border: 1px solid white;
}
<section id="colorBoard">
  <h1>Color Board</h1>
  <div id="red" class="colorWrap">RED</div>
  <div id="green" class="colorWrap">GREEN</div>
  <div id="blue" class="colorWrap">BLUE</div>
</section>

<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
0

Is it possible for you to include the JQuery library in your project/site?

You could use a JQuery event handler on the class instead of iterating through objects to attach the event handler?

This would select all objects of your class "my_color_warpper" with a click event handler to call your logic

$(".mycolor_warpper").on ("click", function () {
// your logic
    callbackFunction2(this.getAttribute("id"));
    callbackFunction1();
 });

Rather than looping through by adding event handler in this way you only declare it once and it slams them all out.