Right now i made this:
<a href="#" title="[+] Add as favorite"><div class="addFavorite"></div></a>
the class="addFavorite", is a normal grey star.
Then i have another class="AlreadyFavorite", that is a yellow star.
I want to make a function, so when you click on the grey star, it sends an ajax call(?) and then on success it turns yellow(changing class to AlreadyFavorite).
I know how to make a onclick function that send a 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;
}
Try not to repeat yourself where possible and avoid unneeded elements:
HTML:
<a href="#" id="fav" title="[+] Add as favorite"> </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);
Clicking the link the first time the url specified in addFav()
will be called and after successful processing the function defined in success will be called. The result:
<a href="#" id="fav" class="active" title="[-] Remove as favorite"> </a>
The second click will call removeFav()
due to the rebinding. The result will be:
<a href="#" id="fav" class="" title="[+] Add as favorite"> </a>
After that it's an endless loop given your server doesn't act out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With