Reputation: 25
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
Reputation: 14891
Two things here
else
is not validspan.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
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
Reputation: 2264
looks like you have an extra semicolon after the if statement:
if () {
} ;
else {
} ;
Neither of those semicolons are needed.
Upvotes: 2