'Using an EventListener on the Element that calls a counter function - Javascript

Goal: Write a function that is called by the eventListener click event of an IMG. The function will use a conditional to see on which ElementID called the function, then initialize the on accumulator to that value, then add 1 and change the innerHTML to show that new value. Key goal is to make this occur with out have 3 similar identical functions

Code Thus Far

let likeCount = !NaN;

var classname = document.getElementsByClassName("like-heart");

function likeCounter() {
/*Note the elementID is very similar to the ELementID of the accumulator element - but not the same.*/
       if (this.getElementById === "ft-recipe-like") {
        likeCount = Number(document.getElementById('featured-likes').innerText);
        likeCount += 1;
        document.getElementById('featured-likes').innerText = likeCount;
    } else if (this.getElementById === "macaroon-like") {
        likeCount = Number(document.getElementById('macaroon-likes').innerText);
        likeCount += 1;
        document.getElementById('macaroon-likes').innerText = likeCount;
    } else if (this.getElementById === 'brulee-like') {
        likeCount = Number(document.getElementById('brulee-likes').innerText);
        likeCount += 1;
        document.getElementById('brulee-likes').innerText = likeCount;
    }    
for (var i = 0; i < classname.length; i++) {
        classname[i].addEventListener('click', likeCounter, false);
    }
}
}
    }
    for (var i = 0; i < classname.length; i++) {
        classname[i].addEventListener('click', likeCounter, false);
    }
}
}



Solution 1:[1]

You can have a map of acc id to Dom node id, and write a generic function to increment the likeCount.

let likeCount = !NaN;

var classname = document.getElementsByClassName("like-heart");

const accIdToDomIdMap = {
  'ft-recipe-like': 'featured-likes',
  'macaroon-like': 'macaroon-likes',
  'brulee-likes': 'brulee-likes'
}

function likeCounter() {
/*Note the elementID is very similar to the ELementID of the accumulator element - but not the same.*/
   if(accIdToDomIdMap.hasOwnProperty(this. getElementById)) {
      const domId = document.getElementById(accIdToDomIdMap[this.getElementById]);
      likeCount = (+domId.innerText || 0) + 1;
      domId.innerText = likeCount;
   }
}
function newFunction() {
    for (var i = 0; i < classname.length; i++) {
        classname[i].addEventListener('click', likeCounter, false);
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kanishk Anand