2

I'm using Adobe Animate CC for a canvas project. I have an array that I assigned events listeners to like so:

for(var i = 0; i < navBtnArray.length; i++ ){
navBtnArray[i].addEventListener("click", navigationControls);
}

What I am trying to figure out is how to capture the index value of the button that was clicked in the array. I tried like so:

function navigationControls(e){

console.log(navBtnArray.indexOf(this));
}

But that keeps returning -1. Again this is Animate CC so I don't have access to jQuery. Animate uses the CreateJS and EaselJS library. I used to use indexOf in AS3, but it doesn't seem to work the exact same way.

icekomo
  • 9,328
  • 7
  • 31
  • 59
  • I was able to get this working by using the currentTarget property. console.log(navBtnArray.indexOf(e.currentTarget) + " this is button array index"); – icekomo Nov 12 '16 at 15:14

2 Answers2

1

For that, you can use:

function navigationControls(e){
    console.log(navBtnArray.indexOf(e.target));
}

If that still doesn't work and indexOf can't compare such objects, you can try adding an extra property to the button objects, like:

for(var i = 0; i < navBtnArray.length; i++ ){
     navBtnArray[i].addEventListener("click", navigationControls);
     navBtnArray[i].index = i;
}

and then do:

function navigationControls(e){
    console.log(e.target.index);
}
Catalin Iancu
  • 722
  • 5
  • 18
  • You might want to consider using `e.currentTarget` instead of `target`, in case the button has children. You can also turn off mouse children using `btn.mouseChildren=false`. – Lanny Nov 14 '16 at 16:35
  • Yes, indeed. Although, I think it's a case-by-case scenario depending how graphics are done, since sometimes I got weird returns from shape children using `e.currentTarget`. – Catalin Iancu Nov 14 '16 at 16:40
0

Try this:

 var navBtnArray = document.getElementsByClassName('demo');
for(var i = 0; i < navBtnArray.length; i++ ){
(function(index){
      navBtnArray[i].onclick = function(){
              console.log(index)  ;
        }    
    })(i);

}
<button class="demo">hi</button>
<button class="demo">hi</button>
<button class="demo">hi</button>
<button class="demo">hi</button>
<button class="demo">hi</button>
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • That looks like a pure javascript approach. I'm using the Animate platform, and there for using a create js / easelJS framework inside of Animate. I found this article, but doesn't seem to solve my issue: http://createjs.com/docs/easeljs/classes/Utility%20Methods.html#method_indexOf – icekomo Nov 12 '16 at 07:44