.addEventListener to multiple elements and give a different output to console

Viewed 26

I recently started to learn the addEventListeners to different Elements and I will like to go forward and have each element log a different value to the console each time they are clicked but my Code does not seem to work. Any suggestions will be appreciated. Please & Thank You.

    var drumButtons = document.querySelectorAll(".drum").length;



    for (var i = 0; i < drumButtons; i++) {


    document.querySelectorAll(".drum")[i].addEventListener("click",    clickerSpecificChecker)};


    function clickerSpecificChecker() {


      if (i === 0) {
        console.log("Clicked w!!!");} 

    else if (i === 1) {
    console.log("Clicked a!!!")} 

    else if (i === 2) {
    console.log("clicked s!!!")} 

    else if (i === 3) {
    console.log("clicked d!!!")} 

    else if (i === 4) {
    console.log("Clicked j!!!")} 

    else if (i === 5) {
    console.log("clicked k!!!")} 

else if (I === 6) {
    console.log("Clicked t!!!")} };
1 Answers

i've found the way out:

let drumButtons = document.querySelectorAll(".drum").length;

for (var i = 0; i < drumButtons; i++) {
    let index = i;
    document.querySelectorAll(".drum")[i].addEventListener("click", () => {
        clickerSpecificChecker(index);
    });
};

function clickerSpecificChecker(i) {
    let words = "wasdjkt";
    words = words.split("");

    console.log(`clicked ${words[i]}!!!`, i);
};

And also made it easier by using array.

The main problem: When you used the clickerSpecificChecker, it took the index after the for loop completed so it took the last index. I've fixed it by giving the argument of the element's index to the function

Related