Toggle heart-shaped html code in javascript

I want to add a heart shaped icon as a button. Click to switch filled / unfilled. I have two - ♡ and ❤ But when I compare it as text. I can not. Because it looks like an image. Here is my attempt:

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?

+4
source share
4 answers

You can compare 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>
Run codeHide result
+5
source

add HTML buttons like

<div>
  <i class="heart fa fa-heart-o"></i>
</div>

Add CSS For This Button

.heart {
  font-size: 25px;
    color:red;
}

Javascript to select and deselect

$(".heart.fa").click(function() {
  $(this).toggleClass("fa-heart fa-heart-o");
});

check jsfiddle demo here

+5
source

: .

solid/light, .

.

EX.  <button class="fa fa-heart"></button>

, ,

0
source

Something like this will give you some idea :) have fun!

JavaScript:

<script>
function setMyFavorite(){
var elem = document.getElementById("circle");
//Gets the RGB value
var theColor = window.getComputedStyle(elem, null).getPropertyValue("background-color");
var hex = rgb2hex(theColor);
 if(hex =="#555555"){
    elem.style.backgroundColor = "#ffffff";
 }
else if(hex =="#ffffff"){
    elem.style.backgroundColor = "#555555";
}
//Convert RGB to Hex value
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
</script>

CSS

 background-color: #555;
 border-radius: 50%;
 border-color:#555;
 border-style: solid;
0
source

Source: https://habr.com/ru/post/1693898/


All Articles