There may be an easier way to do this. But this was what I came up with. In theory, it should work:
So to clear selection, this is one of the ways:
var clearSelection = function(){
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
source: Clear Text Selection with JavaScript
Now we are required to trigger this function for all other iframes except the one that has been made active, when the iframe is clicked, or any text selection has been made in it.
This requires communicating between iframes, which is what complicates it slightly.
Inside each Iframe, put a function that goes like:
//iframe1
document.addEventListener("click", function(){
window.postMessage({
"source": "iframe1"
}, "*");
})
//iframe2
document.addEventListener("click", function(){
window.postMessage({
"source": "iframe2"
}, "*");
})
Now subscribe to these messages in the parent frame like this:
//parent frame
var childrenFrames = window.parent.frames;
window.onmessage = function(e){
if (e.data.source === "iframe1") {
childrenFrames[1].postMessage("clearSelection", "*");
}
if (e.data.source === "iframe2") {
childrenFrames[0].postMessage("clearSelection", "*");
}
};
I got the references to the child iframes using window.top.frames
(to access the top window object) or window.parent.frames
(to access the direct parent window object, while there may be other higher-level ancestors)
[ source: How do I postMessage to a sibling iFrame ]
Now, again, in the children frames, subscribe to the message "clearSelection" like so:
//iframe1, iframe2
window.onmessage = function(e){
if(e.data === "clearSelection"){
clearSelection(); // the method I mentioned in the beginning
}
}
There may be a more straightforward way, but this is the best I could do. Hope this helps.