1

I want to be able to get the x,y coordinates of the end of a text string that has been highlighted in a web browser. I tried searching online for something similar and found that Quora does almost exactly what I want. Their code is obsfucated/ compressed though so I can't work out what they did.

To see any example visit a question on Quora (such as this: http://www.quora.com/Job-Interviews/Whats-the-craziest-thing-you-ever-said-at-an-interview-and-still-got-the-job) and highlight some text in an answer. A little box will pop-up that says 'Embed Quote'. Getting the position of the embedded quote is what I want to do.

I've made a little demo that grabs the mouse position - but I'd like it to be more accurate if possible. There's a jsfiddle of the code here: http://jsfiddle.net/BinaryMoon/zy8hY/

$(function(){
    $(document.body).bind('mouseup', function(e){        
        var selection;
        if (window.getSelection) {
            selection = window.getSelection();
        } else if (document.selection) {
            selection = document.selection.createRange();
        }

        if ( selection.toString().length > 3 ) {
            var tip = $('<div class="pointer" />');
            var p = 
            tip.css({
                'position':'absolute',
                'left': e.pageX,
                'top': e.pageY
            });
            tip.appendTo('.post'); 
        }
    });

    $(document.body).bind('mousedown', function(e){
        $('.pointer').remove();
    });
});
BinaryMoon
  • 95
  • 10
  • 3
    There's an answer here : http://stackoverflow.com/questions/1589721/how-can-i-position-an-element-next-to-user-text-selection/1589912#1589912 – Denys Séguret May 02 '13 at 11:56
  • I spent ages looking for an answer on stackoverflow - must have checked about 15 different questions. Thanks for the tip. I had to modify it but this has done what I wanted! :) – BinaryMoon May 02 '13 at 12:44
  • You're welcome, this wasn't a trivial problem. – Denys Séguret May 02 '13 at 13:03

0 Answers0