-2

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 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Tell me if this helped you out. And if you have'nt seen the tutorial of arrow function, then its not much different than the normal function. So take it like i wrote function () { clickerSpecificChecker(index); }
It worked perfectly. Thank you so much, I really appreciate it. I was somewhat already familiar with ES6 so this was a big refresher!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.