How to Add Custom Scripts in Divi

How to Add Custom Scripts in Divi

Okay, you’ve found some snippets of jQuery or JavaScript code to enhance the functionality of your website but don’t know where to put it. No problem, there are a few options you have.

 

Method 1 – This will run code on every page of the website.

  1. Go to Divi Theme Options > Integration
  2. Enable header code > Enabled
  3. Place your code in the Add code to the < head > of your blog section
  4. Ensure that the code is within <script></script> tags
  5. Placing the code within a document ready functions stops the code running until the page is loaded. jQuery(document).ready(function($){ });

Here is the code for you to copy.


<script>
jQuery(document).ready(function($){

 //This code will check that you have done it correctly
 //An alert box will be displayed on screen when you refresh the browser

 alert("My Script is Working. Yeah, I'm cool!")
 
});
</script>

Method 2 – This will run code only on the page it is required.

  1. Add a Code Module to your section
  2. Add the code as Option 1 to the Content > Text Box

Method 3 – Recommended (This will run code on every page of the website.)

This option is a little more difficult to implement than the others but once done, all scripts are easier to add, change or remove because everything is in the same file and you don’t need to work in the small boxes within Divi. IMPORTANT – This requires a child theme. DO NOT change Divi or WordPress core files because you WILL lose your changes after any update! If you don’t have a blank child theme you can download one here. This has all the files you require.
    1. Open your Child Theme > functions.php file
    2. Add the following code after the opening <?php

function enqueue_divi_parent(){

    //Enqueue Divi
    wp_enqueue_style( 'parent-theme-css', get_template_directory_uri() . '/style.css' );
    wp_enqueue_script( 'custom-jquery', get_stylesheet_directory_uri() . '/custom.js', array( 'jquery' ), '1.0.0' , true );
    
}

add_action( 'wp_enqueue_scripts', 'enqueue_divi_parent' );

  1. You can now use your Child Theme custom.js file for your scripts and your style.css file for your custom styles. Free code editors are available from Brackets and Sublime
  2. Add the code from Option 1 to your Child Theme custom.js file to check that everything works. You WILL NOT require the <script></script> tags for this method.
  3. Let us know in the comments about any issues, successes or preferred methods. We love to hear from you!