0

I'm writing an app using shadow root, I found my self using shadow.children[i].addEventListener('click', fn); so much, so I tried to create a custom function to shorthand it, so I wrote:

var $shadow = function(shadow, el, fn){
  console.log(shadow);
  console.log(el);
var children = shadow.children;
for (var i = 0; i < children.length; i++) {
    var child = children[i];
    console.log('child '+child.id+', el '+el);
       if (child.id === el) {
         console.log('match'); 
         return shadow.children[i].addEventListener('click', fn);
         break;
      }
  }
}

and calling it from the custom element as;

$shadow(shadow, 'd', alert('yap!'));

the problem is the function executed directly once the element is called, and not waiting to "listen" to a "click" action on the specified element.

any thought how to fix it?

1 Answer 1

1
var $shadow = function(shadow, el, fn){
  console.log(shadow);
  console.log(el);
var children = shadow.children;
    console.log(children.length);
for (var i = 0; i < children.length; i++) {
    var child = children[i];
    console.log(children[i]);
    console.log('child '+child.id+', el '+el);
       if (child.id === el) {
         console.log('match'); 
           return shadow.children[i].addEventListener('click', function(){
               console.log(fn);
               fn();
           });
         break;
      }
  }
}
$shadow(shadow, 'd', function(){alert("yap");});

I understand you want to do at this adress..

[http://jsfiddle.net/p4fcoftL/]

I hope you find the job

1
  • Thanks, so it worked by adding the "function(){ }" when I called it, appreciated. Commented Mar 13, 2015 at 13:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.