Home > other >  How to change bootstrap icon's attributes using javascript
How to change bootstrap icon's attributes using javascript

Time:11-29

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/[email protected]/font/bootstrap-icons.css"></head>
<body><div id="posts"></div></body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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/[email protected]/font/bootstrap-icons.css">
</head>

<body>
  <div id="posts"></div>
</body>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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')
}
  • Related