I have a script that requires jQuery, and I don't know how to add it into a post correctly. I've read How to include jQuery and JavaScript files correctly? and Using JavaScript and JQuery in Page but they are too advanced for me to understand. The Scripts 'n Styles plugin has the Include Scripts section, which I suspect is another way to use wp_enqueue_script
, but I don't know which one to choose:
So far, I only add the <head>
and <body>
elements without the jQuery, and while it ultimately worked, it didn't work at the beginning and I had to tried many times. So is there a correctproper and easy way to do this?
FYI: How to add JavaScript code on WordPress correctly?
The code is below.
---–
<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>