I’m having trouble with mouseenter with live element. The functions is not triggered when I hover over a selected element added with javacript.
I add the elements with this:
this.fixElements = function () {
$('.iconstarsdynamic.isgradeable:not(.touched)').each(function(){
var $self = $(this),
$gradeLength = Math.round(parseInt($self.width())/$maxGrade*100)/100;
$self.addClass('touched');
for ($i = 1; $i <= $maxGrade; ++$i) {
$('<span />', {
"class" : "grader",
"z-index" : $i,
"width" : ($gradeLength*$i)+'px'
}).attr('grade', $i).appendTo($self);
}
});
}
And i try to mouseenter with this:
this.hover = function() {
$('.iconstarsdynamic.isgradeable')
.on('mouseenter', '.grader', function(){
$(this).css('visibility', 'visible');
console.log('over');
})
.on('mouseleave', '.grader', function(){
$(this).css('visibility', 'hidden');
});
}
My output looks like this:
<span class="iconstarsdynamic isgradeable touched" title="Rated 0 out of 4">
<span class="stars" style="width:0%;"></span>
<span class="grader" z-index="1" style="width: 9.25px; " grade="1"></span>
<span class="grader" z-index="2" style="width: 18.5px; " grade="2"></span>
<span class="grader" z-index="3" style="width: 27.75px; " grade="3"></span>
<span class="grader" z-index="4" style="width: 37px; " grade="4"></span>
</span>
Problem is that the mouseenter never runs. Why is this? It works if I attach mouseenter to .iconstarsdynamic.isgradeable, but that’s not what I want. I want it attached to .iconstarsdynamic.isgradeable .grader.
The
mouseenterandmouseleaveevents do not bubble up and therefore won’t work with event delegation methods like you use. You should usemouseoverandmouseoutinstead (you may have to take care of descendants’ events, if any).