Home > Net >  How can I access the index of the clicked item?
How can I access the index of the clicked item?

Time:01-17

I'm building a shop section for a school project. It works like a gallery: when clicking on an card, a new display opens up with fullscreen info about the product: img, product title, price... I've managed to match the image of the fullscreen display to the one clicked (you won't see the images since it's a relative URL).

Now I need to match the rest of the info.

const miniaturas = document.querySelectorAll(".galeria a");
const modal = document.querySelector(".modal");
const imgModal = document.querySelector(".modal img");
const plantNames = document.querySelectorAll(".galeria h3")
const plantNameModal = document.querySelector(".modal h3");

miniaturas.forEach(function(miniatura){
    miniatura.addEventListener("click", function(evento){
        evento.preventDefault();
        imgModal.setAttribute("src",miniatura.getAttribute("href"));
        modal.classList.add("visible");

        for(i = 0; i < miniaturas.length; i  ){
            plantNameModal.innerHTML = plantNames[i].innerHTML;
        }
    })
})

modal.addEventListener("click", function(){
    modal.classList.remove("visible");
})

I don't know how to get the innerHTML via each item's index. I've tried using a for loop and the parameter "miniatura" from the function. CodePen here.

CodePudding user response:

You can get the index of each miniatura as the second argument to the handler function you pass to the forEach. You have access to this index within the body of the addEventListener, as in:

miniaturas.forEach(function(miniatura, index){
    miniatura.addEventListener("click", function(evento){
        evento.preventDefault();
        imgModal.setAttribute("src",miniatura.getAttribute("href"));
        modal.classList.add("visible");
      
        // instead of for loop, use `index` to access
        // the corresponding elements in the arrays:
        plantNameModal.innerHTML = plantNames[index].innerHTML;
    })
});

I have forked your Pen.

  • Related