Question

I'm testing a small demo

For example I have a text in tag like this

<body>

good morning, good morning

abcdef ajska
good morning
ssssss
<body>

for example when I select(highlight) the second "good morning", How can I know that, this is 2nd appearence of this text?

if I select "abcdef ajska" , How I can know that this is first time appearence of this text?

So when I select an paragraph , how can I know the order apperence of this paraghaph?

This is an demo about selection,

https://medium.com/what-i-learned-today/2c5ec46b86d0

but I just want to someone use mouse to select an paragraph an promt like alert box will be shown and let me know that the order apperence of selected paraghaph?

Thank you so much. Thanks

Was it helpful?

Solution

I think I understand what you are trying to achieve, I have an idea though it's not solid but maybe this can give you a head start.

Get the highlighted text and find all similar text in the body and wrap it with <span>. Then get the <span> index to determine the highlighted text's occurrence.

We can get that occurrence value by getting the mouse click event coordinates. Then find the <span> located on that coordinates and retrieve its index.

We get the highlighted text with:

var text;
if(window.getSelection){
    text = window.getSelection().toString();
}else if (document.selection && document.selection.type != 'Control'){
    //for IE prior to 9
    text = document.selection.createRange().text;
}

Then check if the text is not empty or not spaces and wrap all similar text with span:

if($.trim(text).length){
    //wrap each word similar to the highlighted text with <span>
    var regex = new RegExp(text,'g')
    $('body').html($('body').html().replace(regex, '<span>'+text+'</span>'));
}

Now it's all wrapped, we need to get the original click coordinates:

$('body').on('click',function(e){
//get the x and y coords
var offset = $(this).offset(),
    x = e.clientX - offset.left,
    y = e.clientY - offset.top,
})

Get the new span located on that coordinates with:

var el = document.elementFromPoint(x, y)

Here is the jsfiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top