0

If the user clicks somewhere in the bar, can the indicator get that width. (Similar to a progress bar in a video)

$(function(){        
  $("#play").click(function() {
    $("#indicador").animate({"width": "150px"}, 8400);
  });
});

Here to try and play:http://jsfiddle.net/SwkaR/7/

Nrc
  • 9,577
  • 17
  • 67
  • 114
  • 1
    This other stack overflow question should help http://stackoverflow.com/questions/4249648/jquery-get-mouse-position-within-an-element – Barry Carlyon Feb 02 '13 at 16:28

3 Answers3

2

You can get the coordinates where the user clicked from the Event object passed as first parameter to the click event handler. You simply have to subtract the element offset relative to the page from $.offset() to get the position relative to the element.

$("#bar").click(function(e) {
    var offset = $(this).offset();
    var relativeX = e.pageX - offset.left;
    var relativeY = e.pageY - offset.top;
    // Do something with these
});

For example, here's a forked fiddle which allows you to place the indicator by clicking anywhere in the bar.

Mattias Buelens
  • 19,609
  • 4
  • 45
  • 51
  • I love this solution because it is so clean and clear and made with just a few lines of code. And the explanation helped a lot to understand. Thank you so much! – Nrc Feb 02 '13 at 17:02
1

I've gone for http://jsfiddle.net/SwkaR/13/ and http://jsfiddle.net/SwkaR/18/

$(function(){

  $("#play").click(function() {
    $("#indicator").animate({"width": "150px"}, 8400);
  });
    $('#bar').click(function(e) {
        var parentOffset = $(this).parent().offset();
         var relX = e.pageX - parentOffset.left;
        $("#indicator").animate({"width": relX + "px"});
    });
    $('#indicator').click(function(e) {
        var parentOffset = $(this).parent().offset();
         var relX = e.pageX - parentOffset.left;
        $("#indicator").animate({"width": relX + "px"});
    });        
});

Set Indicator width to the point where user clicked in the bar

Using jQuery get mouse position within an element as a reference to get the Mouse Click Position in the bar and set indicator to that

Community
  • 1
  • 1
Barry Carlyon
  • 1,039
  • 9
  • 13
0

To get the indicator width, use $("#indicator").width()

JQuery:

$(function(){

  $("#play").click(function() {
    $("#indicator").animate({"width": "150px"}, 8400);
  });

    $("#indicator").click(function() {
        alert($(this).width());
    });

});

Refer LIVE DEMO

Siva Charan
  • 17,940
  • 9
  • 60
  • 95