开发者

jQuery: Making a Favorite button with function?

Right no开发者_如何学运维w 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">&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.


Just change the class to alreadyFavorite after the ajax call? or is there something I am missing?

or is it alreadyFavorit (as in the CSS)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜