• Admin

❤️ A JavaScript "Like" Heart

Kriya Yoga - Single Page App (SPA) features an empty heart glyph ❤️ you can click to turn red. Such simplicity is divine in javascript. The color state of the heart is defined by 2 States of the glyph, an open and a closed heart : "♡": "♥". The color is defined as empty or default and "red".



let glyphStates = {
 "♡": "♥",
 "♥": "♡"
};


let colorStates = {
 "red" : "",
 "": "red"
};


let articleHearts = document.querySelectorAll(".like-glyph");


The Callback function targets the heart, provides an alert and updates the innerText of the HTML. If it is not a success, a .catch function error pop-up renders.



function likeCallback(e) {
 let heart = e.target;
 mimicServerCall()
 .then(function(serverMessage){
 
 alert("Love you too! ❤️🧡💛💚💙💜");
 alert(serverMessage);
 heart.innerText = glyphStates[heart.innerText];
 heart.style.color = colorStates[heart.style.color];
 })
 .catch(function(error) {
 alert("whoops 🙈 Something went wrong!");
 });
}

The EventListener waiting for the click.


for (let glyph of articleHearts) {
 glyph.addEventListener("click", likeCallback);
}




For now, we will mimic a ServerCall function to resolve the call.

function mimicServerCall() {
 return new Promise(function(resolve, reject) {
 setTimeout(function() {
 resolve("Pretend remote server notified of action!");
 }, 300);
 });
}


Link to Github Repo: https://github.com/osxgirl/kriya.git


2 views0 comments

Recent Posts

See All