Hello
Try to use the operator "?" for this instance
Your current code looks like:
function func() {
if (document.getElementById("heart").src == "heart_empty.png")
{
document.getElementById("heart").src = "heart_filled.png";
}
else if(document.getElementById("heart").src == "heart_filled.png")
{
document.getElementById("heart").src = "heart_empty.png";
}
}
Instead, use the "?" operator to compact your function into one line:
Also, instead of getting the element each time, add a script at the bottom of the page that looks like this:
var src = document.getElementById("heart").src;
That will not only decrease lag but also will increase readability of your code
The new script will use the fact that the "?" operator can combine an "if" statement into a one line declaration. To recap, the operator does this:
variable = condition ? /*true*/ : /*false*/
Put your (true) code in the "true" bit and same with the false bit
If the condition is true, then it will set the "variable" to the code written in the "true" bit, otherwise, it will set it to the code written in the "false" bit.
So now with this newfound knowledge, we can update our code!!!
NEW CODE:
function func() {
document.getElementById("heart").src =
document.getElementById("heart").src === "heart_empty.png" ?
"heart_filled.png" : "heart_empty.png";
}
This can be further compacted by using the notation stated above where "src" variable = document.getElementById("heart").src, now it looks like:
function func() {
src = src === "heat_empty.png" ? "heart_filled.png" : "heart_empty.png";
}
Much Better! Now your code is neat, compact and flawless!
=but should use==