0

I have a small icon called "favorite" and when I click on it I call a jquery event handler to change the icon and change the class name.

But when I click on it again it doesnt go to the event handler of the class that I have added to it, it goes back to its original event handler

This is the icon

<input style="float:right" type="image" name="unfavorite" id="unfavorite" class="unfavorite" src="images/unfavorite.png" />

and my jquery is:

    $('.unfavorite').click(function()
    {
        $(this).removeClass('unfavorite');
        $(this).addClass("favorite");
        $(this).attr("src","images/favorite.png");
    });

    $('.favorite').click(function()
    {
        $(this).removeClass('favorite');
        $(this).addClass("unfavorite");
        $(this).attr("src","images/unfavorite.png");
    });

so basically I want to change the icon each time is clicked. But when I addClass(favorite) the event handler for favorite class is never called, it always goes to unfavorite

What should I do?

thank you

beckinho
  • 33
  • 11
  • You bound the event handler to the element. Changing the class of the element doesn't which handler was bound to it. You need to use event delegation to get that effect. – Jason P Oct 21 '13 at 18:58
  • Im a beginner in web development, so I dont really know what that means, or how to fix that. – beckinho Oct 21 '13 at 18:59
  • http://api.jquery.com/toggleClass/ – j08691 Oct 21 '13 at 19:00
  • 2
    Read the docs for [`on()`](http://api.jquery.com/on/), especially the part about direct and delegated events, or search SO for any of the daily similar questions. – Jason P Oct 21 '13 at 19:00

2 Answers2

1

You don't really have to dynamically bind the event. If statements on the element's class can work just fine.

$('#unfavorite').click(function()
{
    $(this).toggleClass('unfavorite');
    $(this).toggleClass("favorite");
    if ($(this).hasClass("favorite"))
        $(this).attr("src","images/favorite.png");
    if ($(this).hasClass("unfavorite"))
        $(this).attr("src","images/unfavorite.png");
});
Gaurav
  • 12,662
  • 2
  • 36
  • 34
0

You need to delegate the event when setting events on dynamically added elements. See http://api.jquery.com/on/. Look at the example below:

$('body').on('click', '.unfavorite', function()
    {
        $(this).removeClass('unfavorite');
        $(this).addClass("favorite");
        $(this).attr("src","images/favorite.png");
    });

$('body').on('click', '.favorite', function()
    {
        $(this).removeClass('favorite');
        $(this).addClass("unfavorite");
        $(this).attr("src","images/unfavorite.png");
    });
T. Junghans
  • 11,385
  • 7
  • 52
  • 75