Search code examples
javascriptif-statementevent-listenerunexpected-token

Javascript Eventlistener unexpected else


Could someone tell me what's wrong with this eventListener? I keep getting unexpected token 'else' on it and don't get why.

JS:

hearts.forEach((span) => span.addEventListener("click", (event) => {
  
  if( heart.classList.contains("liked")){
    $('.photoLikes').each(function() {
      sum = sum + (.35);
    } ) ;
    likeInfo.textContent=  (parseFloat(sum).toFixed(0)) ;
  } ; 
                
  else{
    $('.photoLikes').each(function() {
      sum = sum - (.35);
    } ) ;
    likeInfo.textContent=  (parseFloat(sum).toFixed(0)) ;
  } ; 
}

CodePen with full code(it's the eventlistener in comment at the end of the JS):

https://codepen.io/enukeron/pen/qBaZNbb?editors=1111


Solution

  • Do not put semicolons after if/else statements. They will break the expression, causing the else to not be attached to the if:

    hearts.forEach((span) =>
        span.addEventListener("click", (event) => {
            if (heart.classList.contains("liked")) {
                $(".photoLikes").each(function () {
                    sum = sum + 0.35;
                });
                likeInfo.textContent = parseFloat(sum).toFixed(0);
            } else {
                $(".photoLikes").each(function () {
                    sum = sum - 0.35;
                });
                likeInfo.textContent = parseFloat(sum).toFixed(0);
            }
        })
    );
    

    You were also missing two close-parentheses at the end, which I added in.