50projectsIn50days – Day 29: Double Heart Click
In the HTML, you’ll find a title, h3, and small text, which resemble a cell phone layout.
The entire page listens for click events. When a click event occurs, the createHeart function is triggered, adding the ‘fas’ and ‘fa-heart’ styles to an element. This creates a heart icon on the page, similar to the action seen on Instagram.
const loveMe = document.querySelector('.loveMe');
const times = document.querySelector('#times');
let clickTime = 0;
let timesClicked = 0;
loveMe.addEventListener('click', (e) => {
if (clickTime === 0) {
clickTime = new Date().getTime();
} else {
if ((new Date().getTime() - clickTime) < 800) {
createHeart(e);
clickTime = 0;
} else {
clickTime = new Date().getTime();
}
}
});
const createHeart = (e) => {
const heart = document.createElement('i');
heart.classList.add('fas');
heart.classList.add('fa-heart');
const x = e.clientX;
const y = e.clientY;
const leftOffset = e.target.offsetLeft;
const topOffset = e.target.offsetTop;
const xInside = x - leftOffset;
const yInside = y - topOffset;
heart.style.top = `${yInside}px`;
heart.style.left = `${xInside}px`;
loveMe.appendChild(heart);
times.innerHTML = ++timesClicked;
setTimeout(() => heart.remove(), 1000);
};
You can see the code in this GitHub Repository: 29.double_heart_click and the demo of the project is here: Double Heart Click