I have a simple page with a list of items. I am allowing users to vote on these items, but I only want to allow the user to vote once per. item.
I made a jQuery script that adds a class to the items the user has voted on:
if(!$(this).find(".item span").hasClass("voted")) {
$(".item").hover(function() {
$(this).find(".ratingbar").hide();
$(this).find(".votebar").show();
}, function() {
$(this).find(".votebar").hide();
$(this).find(".ratingbar").show();
});
};
This is the script that prevents the user from voting again on the same item.
$(".votebutton").click(function() {
$("div#"+offerid).find(".item").addClass("voted");
});
This isn’t working. When hovering an item, the hover function still runs even though the second script successfully added the class “voted” to the html.
Why can this be?
You need to use
.live()(or.delegate()) to prevent this, since.hover()attaches to the DOM element, the fact that it’s class changes doesn’t unbind thosemousenterandmouseleaveevent handlers (this is what hover actually binds to).However,
.live()evaluates if the class matches when you hover (because it works off event bubbling, so it checks if the selector matches before executing), and will do what you want, like this:There’s no reason to do the
ifstatement, this will work for all elements and you should only run it once. Previously it was checking if the current item had thevotedclass…but then applying the hover to all.item(nnumber of times) elements for each one that didn’t have the class…instead run this just once outside whatever loop you’re in now, it should be directly in adocument.readyhandler.Edit: You can shorten this as well since you’re just toggling the elements around, using
.toggle(), it’s the same effect, just a bit simpler/more concise: