0

Is it possible to position div at the end of selected text like popup/tooltip somehow? Text is being selected on a page, not in input or textarea.

EDIT: I think I need to clarify, I already have textselect event, I just want to determine the position of the selected text.

EDIT2: I realized that event itself has pageX and pageY cooridnates, so i was just able to grab that and use it for positioning my popup

DavidW
  • 5,069
  • 14
  • 46
  • 68
  • When you say "selected text", are you meaning a text that is selected by the user with the mouse, i.e.? – mariogl Feb 25 '12 at 15:10

3 Answers3

1

jquery select event is limited to input and textarea.

there's no easy way to detect select event on a whole document.although IE has a select event that is implemented on all elements but other browsers have this only for inputs. but you can do it by handling keyup and mouseup events on the your page .

here's an example:

example.Selector = {};
 //each browser has a paricular getSelection .
example.Selector.getSelected = function(){
  var t = '';
  if(window.getSelection){
    t = window.getSelection();
  }else if(document.getSelection){
    t = document.getSelection();
  }else if(document.selection){
    t = document.selection.createRange().text;
  }
  return t;
}

//bind a mouseup event handler to document
example.Selector.mouseup = function(){
  var st = example.Selector.getSelected();
  if(st!=''){ 
     //display yout tooltip or popup here

  }
}

$(document).ready(function(){
  $(document).bind("mouseup", example.Selector.mouseup);
});

here's a working example http://jsfiddle.net/chemouna/k6yVC/

Mouna Cheikhna
  • 38,870
  • 10
  • 48
  • 69
0

take the offset top of the text you want to put the popup above, and decrease it by the height of the popup http://jsfiddle.net/UuGtm/3/

$("#popup").css("top",parseInt($("#text").offset().top)-parseInt($("#popup").height());
Yaron U.
  • 7,681
  • 3
  • 31
  • 45
  • I do not have set #text or anything to get position from, just a selected text on page which could be anywhere. – DavidW Feb 25 '12 at 15:07
  • this is just an example... you can take any element you want in the page, you can also take the mouse y position if it helps you – Yaron U. Feb 25 '12 at 15:09
0

Sorry I don't have time to write a whole thing out, but you might be able to use some combination of a mouseup event listener with window.getSelection() to grab selected text on mouse up. From there you could find its parent element, and append a div with absolute positioning close by the selected text.

Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96