0

I need -

  1. To create a bootstrap icon (heart) when DOM content is loaded
  2. When the icon is clicked, the heart icon fills with red (Here I use heart-fill icon)
  3. Both of the icons to be larger than the original

document.addEventListener('DOMContentLoaded', function () {
      var heart = document.createElement('i')
      heart.className = 'bi bi-heart'
      document.querySelector('#posts').append(heart)
      heart.onclick = function () {
        this.className = 'bi bi-heart-fill'
        this.setAttribute('fill', 'red')
      }
    } )
<head><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"></head>
<body><div id="posts"></div></body>

When I click the heart, it fills with black, not red. I also do not know how to make it larger by increasing the value of width and height. I saw other questions related to this, but none of them solve my problem.

2 Answers2

2

First off, since you used bootstrap icons and they are just working with the CSS content property, you do not have access to the fill property within them so it won't work as expected, alternatively, you should work with color and font-size property to achieve what you looking for.

In order to use it within javascript, You need to use style property and then access their attributes (like color and fontSize) within it. With the same solution, you can change the size of them with the font-size property.

Here is the final product of the above approaches:

document.addEventListener('DOMContentLoaded', function() {
  var heart = document.createElement('i')
  heart.className = 'bi bi-heart'
  document.querySelector('#posts').append(heart)
  heart.onclick = function() {
    this.className = 'bi bi-heart-fill'
    this.style.color = 'red'
    this.style.fontSize = '24px'
  }
})
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
</head>

<body>
  <div id="posts"></div>
</body>
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
1

The tag's content can be treated as text, so you should use the "color" attribute to change the color, and the "font-size" to make it bigger, you can create a class with both this properties on css and asign the class to the element once the icon is clicked.

CSS:

.active { color: red; font-size: 24px }

JS:

(...)
heart.onclick = function() {
  this.classList.add('active')
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 28 '21 at 15:24