Search code examples
javascriptjqueryhtmlcssrating

CSS child width by cursor position on parent


I'm trying to make CSS/jQuery based rating. This is what I have till now: JSFiddle.

<div class="rating">
     <div class="active" style="width: 70%"></div>
</div>

I need to change percent of .rating > .active when mouse cursor is on the parent (.rating). For example I will move my mouse 50% to right so .active will have 50% width.

Example with JS

$('.rating').on('mouseover', function(){    
    var position = $(this).position();

    $(this).find('.active').css('width', position.left);
});

But it always returns me "8". So I don't know why.


Solution

  • http://jsfiddle.net/km2p1ebb/3/

    $(".rating").mousemove(function(e) {
        var gLeft = $(this).offset().left,
            pX = e.pageX;
        $(this).find('.active').width(pX - gLeft);
    });