Manish
Manish

Reputation: 1447

Jquery mouseover and click not working on same element

I have this code , mouseover is working fine but click event is not working

HTML CODE:

<span class="rating">
<span class="rating1 rate" data-rating="1"  title="1"><i class="icon-star-empty" ></i>        </span>
<span class="rating2 rate" data-rating="2" title="2"><i class="icon-star-empty"  ></i></span>
<span class="rating3 rate" data-rating="3" title="3"><i class="icon-star-empty"  ></i></span>
<span class="rating4 rate" data-rating="4" title="4"><i class="icon-star-empty"  ></i></span>
<span class="rating5 rate" data-rating="5" title="5"><i class="icon-star-empty"  ></i></span>

JQUERY

$(document).on('mouseover', '.rate', function () {
   var rating = parseInt($(this).attr('data-rating'), 10);
   var rate = rating + 1;

   for (var j = 1; j < rate; j++) 
      {
       $('.rating' + j).html('<i class="icon-star" title="' + j + '" data-rating="' + j + '"></i>');
      }

   for (var i = rate; i < 6; i++) 
      {
       $('.rating' + i).html('<i class="icon-star-empty" title="' + i + '" data-rating="' + i + '"></i>');
      }
    });


$(document).on('click', '.rate', function () {
  var rate = parseInt($(this).attr('data-rating'), 10);
  alert(rate);
 });

JSFIDDLE http://jsfiddle.net/code_snips/EnjCH/1/

Upvotes: 3

Views: 2360

Answers (2)

PSL
PSL

Reputation: 123739

Try this way:

$('.rate').on('mouseenter', function () {
    var rating = parseInt($(this).attr('data-rating'), 10),
        rate = rating + 1, $rates = $('.rate');
    $rates.find('.icon-star').removeClass('icon-star').addClass('icon-star-empty');
    $rates.filter(':lt(' + ($rates.index(this) + 1) + ')').find('i').removeClass('icon-star-empty').addClass('icon-star ');

});


$('.rate').on('click', function () {
    var rate = parseInt($(this).attr('data-rating'), 10);
    alert(rate);
});

Fiddle

Your issue could be because on mouse over you keep on changing the html and mouse over probably gets triggered over and again and there is no click event gets triggered as the elements which it is over(i) gets changed over and again so your event is lost(click/mouseover actually happens on i which gets bubbled up to the span's handlers). So instead just add/remove class which is what you just want.

Upvotes: 2

mlnyc
mlnyc

Reputation: 2716

This worked for me...

$('.rate').on('mouseover', function () {
    console.log('in mouseover');
});


$('.rate').on('click', function () {
    alert('in click');
});

I'd suggest to keep things simple and first make sure you wired up the event handlers properly. Only then would I add logic since that can complicate things. Take it from the sample above and make sure that works in your application. If so, you can start adding logic to it

Upvotes: 1

Related Questions