0

I want to add small jQuery script in my WordPress how to do that?

Here's the JQuery script that I want to add:

  ( function( window ) {
   'use strict';

  function classReg( className ) {
   return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
  }
   var hasClass, addClass, removeClass;

   if ( 'classList' in document.documentElement ) {
    hasClass = function( elem, c ) {
     return elem.classList.contains( c );
   };
   addClass = function( elem, c ) {
   elem.classList.add( c );
  };
   removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
 }
   else {
   hasClass = function( elem, c ) {
   return classReg( c ).test( elem.className );
 };
 addClass = function( elem, c ) {
   if ( !hasClass( elem, c ) ) {
   elem.className = elem.className + ' ' + c;
  }
 };
  removeClass = function( elem, c ) {
 elem.className = elem.className.replace( classReg( c ), ' ' );
 };
}

function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
 fn( elem, c );
}

var classie = {
  hasClass: hasClass,
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  has: hasClass,
  add: addClass,
  remove: removeClass,
  toggle: toggleClass
};

if ( typeof define === 'function' && define.amd ) {
  define( classie );
} else {
 window.classie = classie;
 }

})( window );

var $ = function(selector){
return document.querySelector(selector);
}
var accordion = $('.accordion');

accordion.addEventListener("click",function(e) {
 e.stopPropagation();
 e.preventDefault();
 if(e.target && e.target.nodeName == "A") {
  var classes = e.target.className.split(" ");
   if(classes) {
  for(var x = 0; x < classes.length; x++) {
    if(classes[x] == "accordionTitle") {
      var title = e.target;

      var content = e.target.parentNode.nextElementSibling;

      classie.toggle(title, 'accordionTitleActive');

      if(classie.has(content, 'accordionItemCollapsed')) {
        if(classie.has(content, 'animateOut')){
          classie.remove(content, 'animateOut');
        }
        classie.add(content, 'animateIn');

      }else{
         classie.remove(content, 'animateIn');
         classie.add(content, 'animateOut');
      }

      classie.toggle(content, 'accordionItemCollapsed');

      }
     }
    }
   }
  });

2 Answers 2

1

If you are going to add a inline script that depends on jQuery, the best and correct way is to use wp_enqeue_scripts action hook, or wp_footer, depends on the situation, combined with wp_script_is() function:

add_action( 'wp_footer', 'cyb_print_inline_script' );
function cyb_print_inline_script() {
  //Check that jQuery has been printed
  if ( wp_script_is( 'jquery', 'done' ) ) {
    ?>
    <script>
        // js code goes here
    </script>
    <?php
  }
}

But you can end up with issues because you are not managing depdencies correctly. The really correct way is to not print inline scripts that has dependencies. Instead, enqueue it in a file.

add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts() {

    wp_enqueue_script(
        //Name to handle your script
        'my-script-handle',
         //URL to the script file
         get_stylesheet_directory_uri() . '/my-script.js',
         //Set the dependencies
         array( 'jquery' ),
         //Version
         '1.0',
         //In footer: true to print the script in footer, false to print it on head
         true
    );

}

If you need to pass variables to your script, use wp_localize_script as follow:

add_action( 'wp_enqeue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts() {

   //Register the js file
    wp_register_script(
        //Name to handle your script
        'my-script-handle',
         //URL to the script file
         get_stylesheet_directory_uri() . '/my-script.js',
         //Set the dependencies
         array( 'jquery' ),
         //Version
         '1.0',
         //In footer: true to print the script in footer, false to print it on head
         true
    );


    //Localize the needed variables
    $script_vars = array(
        'some_var' => 'some value',
        'another_var' => 'another value'
    );
    wp_localize_script( 'my-script-handle', 'object_name_passed_to_script', $script_vars );

    //Enqueue the script
    wp_enqueue_script('my-script-handle');

}
8
  • I follow your instructions but after I edit and reload my website, I'm getting white blank page Commented Feb 16, 2015 at 3:44
  • Which one of the options I proposed you have tried? There was a missing "u" in the function name of the second block of code. Other than that, I don't find any error in the code. Commented Feb 16, 2015 at 7:23
  • I try the second one Commented Feb 16, 2015 at 7:41
  • The function name error is fixed. Try again. Commented Feb 16, 2015 at 7:42
  • I try it, but the script is not working in my wordpress. here's must be the output of that js codepen.io/chriswrightdesign/pen/cmanI Commented Feb 16, 2015 at 7:51
-1

You can add them into functions.php file, code below:

    //load js

    function load_js(){
        if(is_page(Page ID, Page Title or Page Slug)){
        //put your js code here
        }
    }

    add_action('wp_footer', 'load_js', 20); //for footer   
    add_action('wp_head', 'load_js', 8); //for head

or:

function load_js(){
  if(is_page(19)){
     wp_enqueue_script('UniqueName', 'jsfilepath', false, 'version number', true ); // the last parameter true for footer false for head
  }
}

add_action( 'wp_enqueue_scripts', 'load_js')

Code have been tested. It's OK!

3
  • How about I want to use jQuery in specific pages only? Commented Feb 13, 2015 at 8:14
  • Syntax is not right and will lead to errors. Commented Feb 13, 2015 at 8:19
  • I have corrected the code. Now it's Ok! Commented Feb 13, 2015 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.