From What topics can I ask about here?, I think asking about unworkable JS code on WP is not off-topic, because the code should work in principle. But to make sure, is it on-topic?

Below is the draft.


The below js code is meant to swapping a word back and forth when clicking it, and it worked on WP at least two years ago, and it still works on the snippet. But now it doesn't work anymore on my site. Putting it on a test page makes it failed to save. Is there a way to fix it?

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    var words = [];

    words.push('vocabulary');
    words.push('lexicon');
    words.push('lexicons');

  </script>

</head>

<body>

  <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that's added, so don't forget to push 'lexicons' in your array.
  </p>

  <script>
    function toggle(element) {
      if (element.innerHTML.split('_').join('').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
    }

    $.each(words, function(index, value) {
      var replacestr = new RegExp('\\b'+value+'\\b', "g");
      $("p#demo:contains('" + value + "')").html(function(_, html) {
        return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">_______</span>')
      });
    });
  </script>
</body>

</html>
up vote 5 down vote accepted

Your problem is on-topic if it can happen in a WordPress context only. So if you are using WordPress’ JavaScript API in your code, it is on-topic, and if you don't, like in your example, it is not.

  • Can I ask "what could make a functional JS code stop working in WP?"? – Ooker Aug 22 at 2:44
  • 1
    Yes, but after analyzing the logs in your error console carefully. :) – fuxia Aug 22 at 2:48
  • you should have explained that in the answer :(. I got the ReferenceError: words is not defined, but it has been declared already. Does it make a good question? – Ooker Aug 22 at 3:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .