truslivii.lev
truslivii.lev

Reputation: 701

How to use jQuery function on hover

I created jQuery function

function starsMouseMove(n) {
    var i = $(this).offset().left,
        t = Math.floor((n.pageX - i)),
        w;
    if (t > 0 && t < 20) {
        w = 20;
    } else if (t >= 20 && t < 40) {
        w = 40;
    } else if (t >= 40 && t < 60) {
        w = 60;
    } else if (t >= 60 && t < 80) {
        w = 80;
    } else if (t >= 80 && t <= 100) {
        w = 100;
    }
    $(".stars_width", $(this)).css("width", w + "%");
    $(this).parent().find('#rating-input').val(w / 10);
};

and then I try to use it on hover

$('.stars').hover(function (n) {
    starsMouseMove(n);
});

but I get an error

Uncaught TypeError: Cannot read property 'left' of undefined

What's wrong? How to fix it?

Upvotes: 1

Views: 31

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because this within your starsMouseMove function does not refer to the element of the hover event selector, but instead the window. Therefore the offset() is returned as undefined, so calling the left property of that throws the error. If you want to maintain the scope of this within that function you can call it like this:

$('.stars').hover(starsMouseMove);

Alternatively if you'd prefer to keep the anonymous function (if it contains logic besides the call to starsMouseMove for example) you could use $.proxy:

$('.stars').hover(function(e) {
    $.proxy(starsMouseMove, this, e);
});

Or you could amend the function to accept a jQuery object as a parameter, and pass it in:

$('.stars').hover(function(e) {
    starsMouseMove(e, this);
});

function starsMouseMove(n, el) {
    var $el = $(el);

    // rest of your code...
}

Upvotes: 2

Related Questions