Search code examples
javascriptjqueryjquery-load

jQuery script works only once


I have little problem, script works only once, after that I need to refresh page to remove favorite article (script is for that).

$("a.fav_no").on('click', function () {
            var id = $(this).attr("id");
            $(this).load("{$homepage}/user_action.php?action=fav&id="+ id +"").addClass("fav_yes");
        });

$("a.fav_yes").on('click', function () {
            var id = $(this).attr("id");
            $(this).load("{$homepage}/user_action.php?action=remove_fav&id="+ id +"").removeClass("fav_yes");
        });

In console, I get id of article (div) on click after many times on click (so it count) but it doesn't do anything. So I can right now just favorite, to remove from favorites I need to refresh then to click again on link to remove from favorites.

Thanks!


Solution

  • If you use the .on() overload that takes 3 args and is called on the document. Then the events will remain hooked up as UI elements come and go. No need to re add them every time.

    $(document).on("click", "a.offsite", function(){ .....

    See the description of .on() here. http://api.jquery.com/live/