Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Making a Favorite button with function?

Tags:

jquery

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;
}
like image 358
Karem Avatar asked Dec 16 '22 22:12

Karem


1 Answers

Try not to repeat yourself where possible and avoid unneeded 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);

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">&nbsp;</a>

The second click will call removeFav() due to the rebinding. The result will be:

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

After that it's an endless loop given your server doesn't act out.

like image 68
Stefan Hoth Avatar answered Dec 28 '22 23:12

Stefan Hoth