LucR
LucR

Reputation: 25

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

Upvotes: 0

Views: 54

Answers (3)

hgb123
hgb123

Reputation: 14891

Two things here

  • semicolon before else is not valid
  • you missed 2 close parentheses for span.addEventListener( and hearts.forEach(

Modification should be

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)) ;
  }
})) // <-----------

Upvotes: 2

Aplet123
Aplet123

Reputation: 35540

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.

Upvotes: 2

jbeck
jbeck

Reputation: 2264

looks like you have an extra semicolon after the if statement:

if () {
} ;
else {
} ;

Neither of those semicolons are needed.

Upvotes: 2

Related Questions