Reputation: 3805
I am writing a rater script so items can be rated 1 through 5 stars. My script works at first, causing the stars to change from the current rating to whatever they are moused over, and then back to the current rating when they mouse out. But then, hovering back over the stars causes no change. (No clicks in the meantime.)
So hover works, then mouseleave works, then hover no longer works although mouseleave continues to work. Here is my code from the javascript file:
$(document).ready(function(){
$("img.rateImage").hover(function(){
$(this).attr("src","images/vote-star.png");
$(this).prevAll("img.rateImage").attr("src","images/vote-star.png");
$(this).nextAll("img.rateImage").attr("src","images/vote-star-off.png");
});
$("div#invRate").mouseleave(function(){
var rate = $(this).attr("ref");
var i = 1;
var imgs = "";
while (rate > 0){
imgs += "<img class=\"rateImage\" id=\"vote"+i+"\" src=\"images/vote-star.png\" alt=\""+i+"\" style=\"cursor:pointer;\" /> ";
i++;
rate--;
}
while (i < 6){
imgs += "<img class=\"rateImage\" id=\"vote"+i+"\" src=\"images/vote-star-off.png\" alt=\""+i+"\" style=\"cursor:pointer;\" /> ";
i++;
}
$(this).html(imgs);
});
});
And here is the div tag and code where all of this is happening:
<div style="display:block; text-align:center;" id="invRate" ref="<?= $curRate; ?>">
<?
while ($curRate > 0){?>
<img class="rateImage" id="vote<?= $i ?>" src="images/vote-star.png" alt="<?= $i ?>" style="cursor:pointer;" />
<? $i ++;
$curRate --;
}
while ($i < 6){?>
<img class="rateImage" id="vote<?= $i ?>" src="images/vote-star-off.png" alt="<?= $i ?>" style="cursor:pointer;" />
<? $i ++;
}
?>
</div>
Is there any reason the mouseleave event would cause the hover event to stop working? The html that the mouseleave event passes back to the div tag is the exact same html as what is there to begin with. So I'm kind of lost.
Thanks in advance for any suggestions and help.
With Anthony's suggestions, I looked into live() but found that it was deprecated, and that I should use on(). The delegate method also suggested to use on(). So that's what I went with. After getting a couple errors, I realized that my jquery.js was just old, so I updated that and it worked like a charm. I only changed the first line inside of the ready(function(){}) to look like:
$("#invRate").on("hover","img.rateImage",function(){
Upvotes: 1
Views: 193
Reputation: 38345
Your mouseleave
event handler function is replacing the HTML of the div, thereby creating new DOM elements that no longer have the hover
event handler attached to them. You can use jQuery's live()
method to automatically add the event handler to any newly created DOM elements that match the selector.
Upvotes: 1