Karem
Karem

Reputation: 18103

jQuery binding issue

function addFav(){
    $.ajax({
      url: "/favorites/add",
      data: {"id": articleID},
      success: function(){
           $('a#fav')
                 .addClass('active')
                 .attr('title','[-] Remove as favorite')
                 .unbind('click')
                 .bind('click','removeFav')
           ;
      }
    });
}

function removeFav(){
    $.ajax({
      url: "/favorites/remove",
      data: {"id": articleID},
      success: function(){
            $('a#fav')
                 .removeClass('active')
                 .attr('title','[+] Add as favorite')
                 .unbind('click')
                 .bind('click','addFav')
            ;
      }
    });
}

$('a#fav').bind('click','addFav');

This is what i have right now. Nothing happens when i click on a#fav, is it because i need to wrap it in a document.ready? I tried that, but then i get a error, from the jQuery library?? in firebug

d is undefined
Line 49

Upvotes: 2

Views: 185

Answers (1)

karim79
karim79

Reputation: 342635

You should pass the function (and not a string) as the second parameter to bind, e.g.:

$(document).ready(function() {    
    $('a#fav').bind('click', addFav);
});

Be sure to do that within your $(document).ready(... as in the above example, and remember to fix the bind calls within both of your functions.

Upvotes: 1

Related Questions