简体   繁体   中英

Changing color of Font Awesome icon on click: CSS / JavaScript

Forgive me in advance if I'm being stupid here but I'm trying to change the color of 3 Font Awesome icons from white to black when a menu is clicked on my site using JavaScript to add a class of "active" on top of the current class of "social-icon" so that the CSS is activated.

I'm using a div called 'toggle' as a navbar and currently only the first icon is changed to black when this is clicked. I've tried using querySelectorAll instead but that doesn't work and I've also tried moving the social-icon class to within the font awesome icon class but again nothign. I'm just curious at to where I'm going wrong.

Thanks

JS

const menuToggle = document.querySelector('.toggle')
const showcase = document.querySelector('.showcase')
const socialToggle = document.querySelector('.social-icon')

menuToggle.addEventListener('click', function() {
    menuToggle.classList.toggle('active')
    showcase.classList.toggle('active')
    socialToggle.classList.toggle('active')
})

CSS

.social {
    position: fixed;
    bottom: 18px;
    right: 40px;
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
}

.social li {
    list-style: none;
}

.social-icon {
    display: inline-block;
    transform: scale(0.5);
    margin-right: 25px;
    transition: 0.5s;
    font-size: 40px;
    cursor: pointer;
}

.social-icon.active {
color: black;
}

HTML


            <div class="toggle"></div>


<ul class="social">
            <li class="social-icon"><i class="fab fa-facebook-f"></i></li>
            <li class="social-icon"><i class="fab fa-instagram"></i></li>
            <li class="social-icon"><i class="fab fa-tiktok"></i></li>
        </ul>

You can use querySelectorAll to get a node list with all the icons and then iterate them:

const menuToggle = document.querySelector('.toggle');
const showcase = document.querySelector('.showcase');
const socialToggle = document.querySelectorAll('.social-icon');

menuToggle.addEventListener('click', function() {
    menuToggle.classList.toggle('active');
    showcase.classList.toggle('active');
    socialToggle.forEach(function(el) {
        el.classList.toggle('active');
    });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM