Krys
Krys

Reputation: 831

jquery toggle star script

I would like to use the following jquery script to toggle a star link button class on/off which is also dependant on the background image position of an SVG sprite in the CSS.

I have the jquery function below that probably needs some modifications to be more efficient, but how can I make it work for SVG sprite and to update an example page to reflect the on/off toggle setting made by an admin person?

The back-end to the database will be written in C#, but I need to get the front-end working...

$(function() {
$(".star").click(function() {
    var id = $(this).attr("id");

    if($(this).hasClass("starred")) {
        $.post("profilepage.html", {id: id}, function(resp) {
            $(this).removeClass("starred").find("img").attr("src", "star-icon-f.png");
        });
    }

    else {
        $.post("profilepage.html", {id: id}, function(resp) {
            $(this).addClass("starred").find("img").attr("src", "star-icon.png");
        });
    }

    return false;
});
});

Upvotes: 0

Views: 306

Answers (1)

kapantzak
kapantzak

Reputation: 11750

$(".star").click(function() {
    var that = $(this);
    var id = that.attr("id");

    var isStar = false;
    var src = 'star-icon.png';
    if(that.hasClass("starred")) {
        isStar  = true;
        var src = 'star-icon-f.png';
    }

    //Do the post
    $.post("profilepage.html", {id: id}, function(resp) {
        that.find("img").attr("src", src);
        if (isStar) {
            that.removeClass("starred");
        } else {
            that.addClass("starred");
        }
    });

    return false;
});

Upvotes: 1

Related Questions