0

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.

Community
  • 1
  • 1
malditojavi
  • 1,074
  • 2
  • 14
  • 28

1 Answers1

1

Your if should be:

if (window.getSelection().toString() === x.textContent) {

But it seems your function could just return a boolean indicating if the expected text was matched. As you already know the text in that case, it suffices to return true or false. Here is how I would suggest writing it:

function isSelectedText(txt) {
    return window.getSelection().toString().trim() === txt;
}

function doSomethingWhenTextSelected() {
    if (isSelectedText(document.getElementById("titleProduct").textContent)) {
        document.getElementById("hiddenCTA").className = "visibleCTA";
    }
}

document.onmouseup = doSomethingWhenTextSelected;
.hiddenCTA { display: none }
.visibleCTA { display: block }
<h3 id="titleProduct">Title Of Your Product</h3>

hhhh

<div class="hiddenCTA" id="hiddenCTA">Hey, we do price match!</div>
trincot
  • 317,000
  • 35
  • 244
  • 286