0

I'm creating my own lightbox gallery, basically what I need to do is handle the onclick event. So let's say there's a series of <img class="galleryItem" src="path"> the onclick event will pass the index of clicked image to slide changing function (yes I know I can just use $('galleryItem').click() in JQuery but I'm trying to do this in vanilla JS.

I came along a for loop to indicate which class member has been clicked but the script stops to work cause the loop just ends. The code was like:

var members = document.getElementsByClassName('galleryItem'); 
for(var i = 0; i < memebers.length; i++) { 
    members[i].onclick = function memberOnclick() { 
        console.log(i) 
    } 
} 

I also tried members.addEventListener("click", memberOnclick); in for loop but still can't get it to return the index of clicked member. I can imagine the solution to this problem is easy but I kinda out of ideas how to make this work

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
B0re
  • 239
  • 1
  • 8
  • You should investigate event delegation. You can do everything you need to do with one click event handler on the parent element that contains the images. – Randy Casburn May 14 '18 at 20:11

1 Answers1

0

You can use querySelectorAll() instead and loop through each element like this:

members = document.querySelectorAll('.galleryItem');

function someFunc() {
     console.log(this);
    //add your function scripts here
}

members.forEach(member => {
    member.addEventListener('click', someFunc)
});

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
  • okey this worked for indicate that member was clicked but I have another problem unless the function is just something like `console.log(this);` it works fine but when I bring the big guns like lightbox generation function it seems to freeze after 1st use of the code you wrote I'm kinda confused why that happens – B0re May 14 '18 at 20:41
  • That sounds like a different issue altogether since this is the standard way of looping through elements in querySelectorAll. Can you please open a new question with the relevant snippets of your lightbox function. – AndrewL64 May 14 '18 at 20:44
  • the code that seems to freeze the function is `document.body.innerHTML += '
    Caption
    ';` but I have this one in if statment so it happens once only when it is creating the box element in body tag. after leaving the console.log(this) in the part after if statment the function freezes and doesn't want to execute more than 1 time. Any ideas?
    – B0re May 14 '18 at 20:50