Search code examples
jquerycssaddclassremoveclasstoggleclass

How to add and remove classes in jq?


Hello please solve my problem.. searching for hours but no proper and working solution found so finally I decided to post it here.

Here is HTML

<body>
    <div id="first">
            <img src="Untitled-1.png" width="300px" height="300px">
            <img src="Untitled-1.png" width="300px" height="300px"> <br>
            <button id="start" >START</button>
            <button id="stop">STOP</button>
            <button id="slow" >SLOW</button>
            <button id="fast" >FAST</button>   
    </div>     
</body>

here is my CSS:

<style>
.anim{      
    animation-name:test;
    animation-delay:0s;
    animation-direction:normal;
    animation-timing-function:linear;
    animation-duration:500ms;
    animation-iteration-count:infinite;     
    }
    .slow{      
    animation-name:test;
    animation-delay:0s;
    animation-direction:normal;
    animation-timing-function:linear;
    animation-duration:1500ms;
    animation-iteration-count:infinite;     
    }
    .fast{      
    animation-name:test;
    animation-delay:0s;
    animation-direction:normal;
    animation-timing-function:linear;
    animation-duration:200ms;
    animation-iteration-count:infinite; 
}

@keyframes test{
    0%{transform:rotateZ(0deg);}
    50%{transform:rotateZ(180deg);}
    100%{transform:rotateZ(360deg);}
}  
</style>

Here is jQuery:

$(document).ready(function(){ 
        $('#first').on('click','#start',function(){
        $('img').addClass('anim');
        });

        $('#first').on('click','#stop',function(){
        $('img').removeClass();
        });

        $('#first').on('click','#slow',function(){
        $('img').removeClass().addClass('slow');

        });

        $('#first').on('click','#fast',function(){
        $('img').removeClass().addClass('fast');
        });     

});

Look at the jQuery.. I want to change the class (whichever is applied) to another class depending upon the button being pressed. If the "slow" button is pressed, existing class should be removed and a '.slow' class should be applied. i tried all suggested methods on internet and even on this forum but didn't worked. I tried this code as suggesties by others

$('#first').on('click','#slow',function(){
$('img').removeClass().addClass('slow');});

but not working.


Solution

  • Finally i managed to solve this issue.. Actually i was using 'prefix-free.js' which was not correctly coded for chrome. Once i changed the browser and run that code on firefox, it worked perfectly. Due to that prefex-free.js i didn't apply -webkit- or -moz-. Well Thanks all who participated..

    EDITED: Sorry that prefix-free.js has nothing to do with this issue. The issue was due to CHROME browser. I have reported this problem to the developers of chrome. I hope they will resolve the issue on priority basis.