javascript - Need help manipulating class with jquery -
i need code:
$(document).ready(function() { $(".fav").click(function() { $(".fav").removeclass("fav").addclass("fav_"); }); $(".fav_").click(function() { $(".fav_").removeclass("fav_").addclass("fav"); }); });
on click in .fav
div
, transforms .fav_
, vice-versa. ok, problem is: if click 1 time .fav
class, transform .fav_
. if click 1 time more, don't transform again .fav
.
i tried put 1 var check. ex:
- if clicked 1 time:
fav=true
- if clicked 2 times:
fav=false
but doesn't work.
i understand jquery, usual language php, perhaps thence difficulty.
you need keep reference dom elements in variable, , use that. way don't have perform jquery selector again.
$(document).ready(function() { var favs = $(".fav"); favs.click(function() { favs.toggleclass("fav"); favs.toggleclass("fav_"); }); });
you can use toggleclass() method add/remove classes. if tests fav
should toggle , forward between fav
, fav_
. there no need if statements.
edit:
if want toggle showing of background image, don't have remove fav
css class. toggle fav_
it's background override fav
because it's lower in css source.
$(document).ready(function(){ $(".fav").click(function(){ $(this).toggleclass("fav_"); }); });
Comments
Post a Comment