Home > database >  Swapping font awesome icon at runtime
Swapping font awesome icon at runtime

Time:11-01

Swapping font awesome icon at runtime - I'm trying to swap out the Font Awesome sun and moon icons at runtime using the following JavaScript code but I can't seem to get it to work.

I'm calling Font Awesome from a local folder instead of a repository. I have confirmed the fonts are being loaded.

<head>
    <style>
        body {
            padding:10% 3% 10% 3%;
            text-align:center;
        }
        img {
            height:140px;
            width:140px;
        }
        h1 {
            color: #32a852;
        }
        .mode {
            float:right;
        }
        .change {
            cursor: pointer;
            border: 1px solid #555;
            border-radius: 40%;
            width: 20px;
            text-align: center;
            padding: 5px;
            margin-left: 8px;
        }
        .dark {
            background-color: #222;
            color: #e6e6e6;
        }
    </style>
    
</head>
 
<body>
    <div >
        Dark mode:            
        <span >OFF</span>
    </div>

     
    <script>
        $( ".change" ).on("click", function() {
            if( $( "body" ).hasClass( "dark", "fa-solid fa-moon")) {
                $( "body" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( "body" ).addClass( "dark", "fa-solid fa-sun" );
                $( ".change" ).text( "ON" );
            }
        });
    </script>
</body>

CodePudding user response:

You can do this with pure js:

const change = document.querySelector('.change')

change.addEventListener('click',function(){
        change.classList.toggle('dark')
        change.classList.toggle('fa-solid-fa-moon')
        change.classList.toggle('fa-solid-fa-sun')
        if (change.textContent === 'OFF') {
                change.textContent = 'ON'
        } else {
                change.textContent = 'OFF'
        }
})
  • Related