How to include jQuery properly?

assuming you have enqueued everything ( script files and style files ) properly in your wordpress theme’s folder

following would be ( just assume ) your theme files

wp-content/themes/your-theme-dir/
                   assets/
                      css/   ( this is directory/folder )
                        styles.css  ( this is file )
                      js/
                        scripts.js
                   index.php
                   functions.php

lets say your code shown above is in index.php

now assuming you’ve included your scripts.js file from functions.php file

the content in your scripts.js file should look like:

(function($){
    var words = [];

    words.push('vocabulary');
    words.push('lexicon');
    words.push('lexicons');
    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>')
      });
    });
})(jQuery);

Remember when enqueunig scripts your file should be dependent upon jquery like

wp_enqueue_script( 'file-id', 'path-to-file', array( 'jquery' ), 'version-number', 'true' );

for getting path to file, you have two options

  1. if your theme is parent theme use: get_template_directory_uri()
    e.g. get_template_directory_uri().’/assets/js/scripts.js’

  2. if your theme is child theme use: get_stylesheet_directory_uri()
    e.g. get_stylesheet_directory_uri().’/assets/js/scripts.js’

Leave a Comment