Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle heart shaped html code in javascript

I want to add a heart shaped icon as a button. On a click of it should toggle filled/non-filled. I got two - ♡ and ❤ But when I am comparing it as a text. I cant. Because it appears as an image. Here is my try:

function setMyFavorite(){
 alert('SetMyFavorite for '+ $("#heart").html());
 if($("#heart").html()=="♡"){
    $("#heart").html("❤");
 }

 if($("#heart").html()=="❤"){
        $("#heart").html("♡");
 }
}

Here is my HTML code

<div id="heart" title="Set as Favorite" onclick="javascript:setMyFavorite();">&#9825;</div>

How Can I compare it?

like image 444
Ninad Pingale Avatar asked Dec 13 '22 18:12

Ninad Pingale


1 Answers

You can compare using the unicode characters.

const whiteHeart = '\u2661';
const blackHeart = '\u2665';
const button = document.querySelector('button');
button.addEventListener('click', toggle);

function toggle() {
  const like = button.textContent;
  if(like==whiteHeart) {
    button.textContent = blackHeart;
  } else {
    button.textContent = whiteHeart;
  }
}
<button>♡</button>
like image 179
Agney Avatar answered Dec 17 '22 22:12

Agney