Toggle font awesome class on button click

后端 未结 7 670
心在旅途
心在旅途 2020-12-31 22:37

I have the code as here in this jsfiddle, I want the font awesome icon to change on button click using javascript, but it does\'nt seem to work. I\'m new to javascript so pl

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 23:16

    I would split my comment into multiple remarks:

    1/ As mentioned in the other comments: $("#favIcon").toggleClass('fa-star-o fa-star'); This is a mix of JS and JQuery calls. If you want to use pure JS you would use:

    document.getElementById("favIcon").classList.toggle('fa-star-o');
    

    If you want to use JQuery you can use () As mentioned in Difster's comment:

    $("#favIcon").toggleClass('fa-star-o');
    

    2/ As mentioned already in the comments, it's better to attach an event listener.

    Your Fiddle js would look like this:

    document.getElementById("favBtn").addEventListener("click", fav);
    function fav() {
        document.getElementById("favIcon").classList.toggle('fa-star-o');
        document.getElementById("favIcon").classList.toggle('fa-star');
    }
    

    And remove the "onClick" on the HTML since you would be attaching a js event listener.

    Links to check: JQuery toggleClass - js classList

提交回复
热议问题