Jenny Jenny - 6 months ago 19
Javascript Question

How to change html class after ajax successful response?

I want to toggle the voting arrow class, the same way as stackoverflow's voting arrow. For a logged in user, if already voted up, the html is:

<a href="#vote" id="vote-up-%1$d" class="vote vote-up-on"></a>
<a href="#vote" id="vote-down-%1$d" class="vote vote-down-off"></a>


After user clicked down arrow, if response success, How to change "vote-up-on" to "vote-up-off", and change "vote-down-off" to "vote-down-one"?

Answer

Make a callback function when you receive Ajax response.

function addVoteUpClass() {
    if (jQuery(".vote").hasClass("vote-up-on")) {
        jQuery(".vote-up-on").removeClass("vote-up-on").addClass("vote-up-off");
    }
}

jQuery.ajax({
    url: "your_url",
    method: "GET",
    success: function(data) {
        addVoteUpClass();
    }
});
Comments