I can’t explain the behaviour of the code below. Here’s my entire script
<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var tmpText = '';
$(document).ready(function(){
tmpText = '';
$('#btn_bold').click(function(){alert(tmpText);});
$('textarea').bind('mouseup', function(){
tmpText = '';
if(window.getSelection){
tmpText = window.getSelection();
}else if(document.getSelection){
tmpText = document.getSelection();
}else if(document.selection){
tmpText = document.selection.createRange().text;
}
//tmpText = 'hello world';
alert(tmpText);
});
});
</script>
</head>
<body>
<button type="button" id="btn_bold">click</button>
<textarea>This is some text</textarea>
</body>
</html>
Try the following operations:
1) Use your mouse to high light text in the text area. You will notice that javascript alerts you the selected text.
2) Press the click button. You will notice javascript will alert you an empty string.
No uncomment tmpText = 'hello world'; and repeat the above steps. This time, you’ll notice both steps 1) and 2) alerts you “hello world”.
How come in the first experiment, step 2) does not alert you the same text as step 1)?
I am testing in google chrome
Because it doesn’t automatically get converted to string. When you call it straight with alert(), it runs the toString on it, but when you assign to a variable to be later used, it keeps it as selection object and when you try to alert it later on, you presumably won’t have that selection active anymore (because you just clicked the button).
Add toString() at the end of each of those selections and it should work as intended.
example on jsfiddle
I recall this being explained quite well in the mozilla developer pages under the getSelection bit, if you want a better explanation why it is like this.
EDIT: found the link to the page on mozilla, specifically check what they say under “Notes”.