tags:

views:

40

answers:

3

I have a simple jQuery image switch that is failing.

$('.heart_img').click(function()
    {
        var heart_type = $(this).attr('src');

        //alert( heart_type );

        if ( heart_type == 'images/unheart.png')
        {
            //alert('uheart');
            $(this).attr('src','images/heart.png');
        }
        else if ( heart_type == 'images/heart.png');
        {
            $(this).attr('src','images/unheart.png');
        }

    });

The alerts fire correctly when not commented out so and the images are in the correct place so I am not sure what the problem is.

A: 

@ian, the image may be in the correct place but the src can't see it. try something like "//images/unheart.png"

griegs
+6  A: 

Problem:

Semicolon in your if else

else if ( heart_type == 'images/heart.png');

should be

else if ( heart_type == 'images/heart.png')

even better

else
Peter Ajtai
lol!... +1 for your eyes man!
Reigel
Yes! Thanks for that.
ian
A: 

this is not an answer but for improvements... if you're in jQuery 1.4, you can

$('.heart_img').click(function(){
     $(this).attr('src', function(index,heart_type){
        if ( heart_type.indexOf('unheart.png') != -1 )
        {
            return 'images/heart.png';
        }
        else if ( heart_type.indexOf('heart.png') != -1 )
        {
            return 'images/unheart.png';
        }
        return heart_type;
     });
});

or much better,

$('.heart_img').click(function(){
     $(this).attr('src', function(index,heart_type){
            return ( heart_type.indexOf('unheart.png') != -1 )? 'images/heart.png':'images/unheart.png';           
     });
});
Reigel