I'm trying to access a global variable in two Javascript methods. The first one is supposed to write to the variable and the second one is supposed to read it.
I have the following code:
var selectedObj;
function first(){
selectedObj = window.getSelection();
alert(selectedObj);
}
function second(){
alert(selectedObj);
}
So the user selects some text in an contenteditable textbox. When function first() runs, it does in fact display what was selected. So I know its value is going into the global variable selectedObj.
But before running function second(), the selected text becomes unselected. However, nothing happens that explicitly sets the value of selectedObj. Ergo, I would expect it to still retain the value of what was previously selected by the user.
But it doesn't. When the function second() runs, the alert is empty.
The alert won't be empty if the user doesn't deselect the text, so I know the global variable can work. But I need it to retain its value even if the user deselects the text.
How can I make this happen?
Like someone else suggested, setting it to a local variable (by value instead of reference) seems to work.
var selectedObj;
function first() {
let newSelection = window.getSelection().toString();
selectedObj = newSelection;
alert(selectedObj);
}
function second() {
alert(selectedObj);
}
Lorem ipsum yada yada
<button onclick="first()">First</button>
<button onclick="second()">Second</button>