i'm just trying to add or remove a class for an icon using bootstrap.
I know my code is bad and i need to improve it, here is why i'm asking your help. I know it can be reduce by using this, but i don't know how to do with the name of the classes than.
Here is my code :
heart = document.getElementById('heart');
chart = document.getElementById('chart');
heart.addEventListener('click', function(){
if(heart.classList.contains('bi-heart-fill')){
heart.classList.add('bi-heart');
heart.classList.remove('bi-heart-fill');
heart.style.color='white';
}
else{
heart.classList.add('bi-heart-fill');
heart.classList.remove('bi-heart');
heart.style.color='#1DB954';
}
})
chart.addEventListener('click', function(){
if(chart.classList.contains('bi-bar-chart-fill')){
chart.classList.add('bi-bar-chart');
chart.classList.remove('bi-bar-chart-fill');
chart.style.color='white';
}
else{
chart.classList.add('bi-bar-chart-fill');
chart.classList.remove('bi-bar-chart');
chart.style.color='#1DB954';
}
})
Thanks you !
A big part in programming is Don't Repeat Yourself (DRY).
In your case you can easily create a function which toggles the classes. All you have to do is pass the right parameters.
heart = document.getElementById('heart');
chart = document.getElementById('chart');
function toggleIcon(element, activeClass, inactiveClass) {
if (element.classList.contains(activeClass)) {
element.classList.add(inactiveClass);
element.classList.remove(activeClass);
element.style.color = 'white';
} else {
element.classList.add(activeClass);
element.classList.remove(inactiveClass);
element.style.color = '#1DB954';
}
}
heart.addEventListener('click', function() {
toggleIcon(heart, 'bi-heart-fill', 'bi-heart');
})
chart.addEventListener('click', function() {
toggleIcon(chart, 'bi-bar-chart-fill', 'bi-bar-chart');
})
A concise way to fix this is using element.classList.toggle:
heart.addEventListener('click', function(){
heart.classList.toggle('bi-heart-fill');
heart.classList.toggle('bi-heart');
heart.style.color = heart.classList.contains('bi-heart') ? 'white': '#1DB954'
})
chart.addEventListener('click', function(){
chart.classList.toggle('bi-bar-chart-fill');
chart.classList.toggle('bi-bar-chart');
chart.style.color = chart.classList.contains('bi-bar-chart') ? 'white': '#1DB954'
})
If you can add some CSS you can make it even more efficient.
#heart {
color: white;
}
#heart.black {
color: #1DB954;
}
then
heart.addEventListener('click', function(){
heart.classList.toggle('bi-heart-fill');
heart.classList.toggle('bi-heart');
heart.classList.toggle('black');
})