Search code examples
htmljquerycssanimationkeyframe

Cant find the way to use a Keyframe animation via Jquery (.css, .animate)


My html

        <fieldset class="field_one">
            <legend>Character Creation <i class="fa-solid fa-signs-post"></i></legend>
            <div id="message">...............</div>
            <img src="./image/index1.png" id="mainImage" alt="">
            <div class="button"><a href="#" id="btnImage">¡Generate Character!</a></div> 
            <div class="button"><a href="#" id="btnName">¡Generate Nickname!</a></div>
        </fieldset>

My css keyframe

@keyframes rainbow {
    0%   {color:red;}
    25%  {color:blue;}
    50%  {color:gold;}
    75%  {color:greenyellow;}
    100% {color:red;}
}

My jquery js

$('fieldset').hover(function() {
        $(this).css({"animation":"rainbow","font-size":"18pt"}, 1000);
});

Is for a work i need to do and i cant really find a way to make it work with jquery (i know that is way easier with plain css)


Solution

  • Set a class with your animation rules and then use addClass()

    $('fieldset').hover(function() {
       $(this).addClass('rainbowAnim');
    });
    @keyframes rainbow {
        0%   {color:red;}
        25%  {color:blue;}
        50%  {color:gold;}
        75%  {color:greenyellow;}
        100% {color:red;}
    }
    .rainbowAnim {
      -webkit-animation: rainbow 5s infinite;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <fieldset class="field_one">
        <legend>Character Creation <i class="fa-solid fa-signs-post"></i></legend>
        <div id="message">...............</div>
        <img src="./image/index1.png" id="mainImage" alt="">
        <div class="button"><a href="#" id="btnImage">¡Generate Character!</a></div> 
        <div class="button"><a href="#" id="btnName">¡Generate Nickname!</a></div>
    </fieldset>