Strange choice behavior

My JS code is:

function getSelectedText(){ if(window.getSelection){ select = window.getSelection().getRangeAt(0); var st_span = select.startContainer.parentNode.getAttribute("id").split("_")[1]; var end_span = select.endContainer.parentNode.getAttribute("id").split("_")[1]; console.log(select.endContainer); var ret_urn=[st_span,end_span]; return ret_urn } else if(document.getSelection){ return document.getSelection(); } } $(document).ready(function() { $("div#check_button button").click(function () { var loc = getSelectedText(); console.log(loc); }); }); 

Here is my entire html file: http://pastebin.com/acdiU623

It’s hard to explain this, so I prepared a short film: http://www.youtube.com/watch?v=tVk4K70JO80

In a few words: when I press the left mouse button and hold it to select text / numbers and start selecting from half a letter / number, although this letter / number is not highlighted, it is added to the selection. I have to start choosing exactly. This is normal with capital letters, but with letters like i, j, or l.

This is the second example of my film. I pressed the left button 3/4 of the length of number 5, although 5 is not highlighted, it is selected.

Tested in FF and Opera.

+4
source share
2 answers

Ok, just tried this demo. and it works flawlessly. It even works on firefox. Just a proven opera and safari, and it works on both of them. Even if I select half the letter or number, it just returns the selected text, which is expected when you make the selection.

try it on a new webpage though for testing. then when it works and you are satisfied with the results, then proceed to make changes to the existing page.

This is much simpler than your code. This is a cross browser script to get the text selected by the user

 <script language=javascript> function getSelText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); } else if (document.selection) { txt = document.selection.createRange().text; } else return; document.aform.selectedtext.value = txt; } </script> <input type="button" value="Get selection" onmousedown="getSelText()"> <form name=aform > <textarea name="selectedtext" rows="5" cols="20"></textarea> </form> 

http://www.codetoad.com/javascript_get_selected_text.asp

Hope this helps.

PC

+1
source

There are several different boundary points for selection that will look the same to the user. You probably see the difference between the following, where | - selection border:

 <span>5</span><span>|6</span><span>7|</span><span>8</span> 

and

 <span>5|</span><span>6</span><span>7</span><span>|8</span> 

In both cases, calling toString() choice will give you the same result ("67").

0
source

All Articles