jQuery toggle() with unknown initial state

Posted by Jason Morhardt on Stack Overflow See other posts from Stack Overflow or by Jason Morhardt
Published on 2010-03-11T18:14:10Z Indexed on 2010/03/11 18:19 UTC
Read the original article Hit count: 171

Filed under:

I have a project that I am working on that uses a little image to mark a record as a favorite on multiple rows in a table. The data gets pulled from a DB and the image is based on whether or not that item is a favorite. One image for a favorite, a different image if not a favorite. I want the user to be able to toggle the image and make it a favorite or not. Here's my code:

$(function () {
    $('.FavoriteToggle').toggle(
      function () {
        $(this).find("img").attr({src:"../../images/icons/favorite.png"});
        var ListText = $(this).find('.FavoriteToggleIcon').attr("title");
        var ListID = ListText.match(/\d+/);
        $.ajax({
            url: "include/AJAX.inc.php",    
            type: "GET",
            data: "action=favorite&ItemType=0&ItemID=" + ListID,        
            success: function () {}     
        });
      },
      function () {
        $(this).find("img").attr({src:"../../images/icons/favorite_not.png"});
        var ListText = $(this).find('.FavoriteToggleIcon').attr("title");
        var ListID = ListText.match(/\d+/);
        $.ajax({
            url: "include/AJAX.inc.php",    
            type: "GET",
            data: "action=favorite&ItemType=0&ItemID=" + ListID,        
            success: function () {}     
        });
      }
     );
});

Works great if the initial state is not a favorite. But you have to double click to get the image to change if it IS a favorite initially. This causes the AJAX to fire twice and essentially make it a favorite then not a favorite before the image responds. The user thinks he's made it a favorite because the image changed, but in fact, it's not. Help anybody?

© Stack Overflow or respective owner

Related posts about jQuery