I'm trying to set a variation of this Javascript: How to detect if a word is highlighted , but I'd like to run the function getSelectedText only if the selected text matches the value of the h1 id
The code I set looks like:
function getSelectedText() {
var x = document.getElementById("titleProduct");
var text = "";
if (typeof window.getSelection === x) {
alert('hey');
text = window.getSelection().toString();
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
document.getElementById("hiddenCTA").className = "visibleCTA";
}
}
var x = document.getElementById("titleProduct");
document.onmouseup = doSomethingWithSelectedText;
I included the alert('hey') inside that if loop to see that is running, just for testing but there is no evidence of it in my tests, nor I can see any errors in the console. The whole code is in http://codepen.io/malditojavi/pen/LWmRvp?editors=1010
In this case, the function should only run if the full string 'Title Of Your Product' is selected, not any other text within the HTML document.