...">

JQuery: Creating a favorite button with a function?

Now I have done this:

<a href="#" title="[+] Add as favorite"><div class="addFavorite"></div></a> 

class = "addFavorite", is a normal gray star.

Then I have one more class = "AlreadyFavorite", that is, a yellow star.

I want to make a function, so when you click on the gray star, it sends an ajax (?) Call, and then upon successful completion turns yellow (changing the class to AlreadyFavorite).

I know how to create an onclick function that sends an ajax call, but how do I change the style / change the image icon to yellow?

CSS

 .addFavorit{ background: url('../images/addFavorit.png'); width: 48px; height: 48px; } .alreadyFavorit{ background: url('../images/addFavorit_hover.png'); width: 48px; height: 48px; } 
+4
source share
2 answers

Try not to repeat where possible and avoid unnecessary elements:

HTML:

 <a href="#" id="fav" title="[+] Add as favorite">&nbsp;</a> 

CSS

 a#fav{ background: url('../images/addFavorit.png'); display: block; width: 48px; height: 48px; } a#fav.active{ background: url('../images/addFavorit_hover.png'); } 

JAVASCRIPT

 function addFav(){ $.ajax({ url: "/favorites/add", data: {"id": articleID}, success: function(){ $('a#fav') .addClass('active') .attr('title','[-] Remove from favorites') .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) ; } }); } //this will make the link listen to function addFav (you might know this already) $('a#fav').bind('click', addFav); 

By clicking on the link on the first call to the url specified in addFav() , and after successful processing, the function defined as a result will be called. Result:

 <a href="#" id="fav" class="active" title="[-] Remove as favorite">&nbsp;</a> 

A second click will call removeFav() due to overwriting. The result will be:

 <a href="#" id="fav" class="" title="[+] Add as favorite">&nbsp;</a> 

After that, the endless loop set by your server does not work.

+10
source

Just change the class to alreadyFavorite after calling ajax? or is something missing?

or is it alreadyFavorit (as in CSS)

 $('div').removeClass('addFavorit').addClass('alreadyFavorit') 
0
source

All Articles