John Smith John Smith - 7 months ago 11
Javascript Question

Change class on click not working?

Trying to change the class of an item with jQuery, but I can't seem to make it work. For some reason, nothing at all is happening.

Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$("#theSpinner").click(function() {
$("#theSpinner").toggleClass("spinning");
});
</script>

<a href="#" id="reload">
<img src="spinbut.png" style="width:100px;height:100px;" id="theSpinner" class="notspinning">
</a>


I've tried with:

$("#theSpinner").click(function() {
$("#theSpinner").removeClass("notspinning");
$("#theSpinner").addClass("spinning");
});


aswell as
$("#reload")
instead of
$("#theSpinner")
, and with an
onClick=""
to a javascript function containing the addClass / removeClass part.

I really don't know what's the problem, but any way around this bull would make me very happy.

Answer

Try wrapping your jQuery code within a "document-ready" block to ensure that jQuery has been loaded prior to calling your function :

<script>
    // Example of a document ready function
    $(function(){
        // When jQuery has loaded, wire up this function
        $("#theSpinner").click(function() {
            $(this).toggleClass("spinning");
        });
    });
</script>

Example

You can see a working example of this in action here and demonstrated below :

enter image description here