Adding Custom Javascript

If you already have a way to add custom javascript to your site, you can use that. Otherwise, you can follow this guide to create and enqueue a custom JS file for your Bellows customizations.

Where to add your custom Javascript Code

While there are many places you could put your code, a common solution is to add it to a child theme. You should never edit a plugin or theme directly since these may be updated and overwrite your changes in the future. Adding code in a child theme will preserve your changes.

If you’re not sure how to set up a child theme, this plugin can generate one for you: Child Theme Configurator

Creating a custom javascript file: bellows-custom.js

In your child theme, create a bellows-custom.js file. If you wish to place this in a subfolder (such as assets/js), be sure to adjust the paths accordingly in the enqueue code in step 3.

Inside your new file, here’s some sample code to get you started:

(function($){
  //place your custom code here
})(jQuery);

This will run your custom code when the site loads, after Bellows has been initialized.

Add your custom code where it says “place your custom code here”.

Enqueuing your new JS file

So far we’ve created the file, now we need to tell WordPress actually to load it on your site. To do this, add this PHP in your child theme functions.php file.

function bam_enqueue_custom_assets(){
    $dir = get_stylesheet_directory_uri();
    wp_enqueue_script( 'bellows-custom-js' , $dir.'/bellows-custom.js' , array( 'bellows' ) ,  false , true );
}
add_action( 'wp_enqueue_scripts' , 'bam_enqueue_custom_assets' , 25 );

Minify and concatenate your JS files (optional)

Separating your scripts into individual files per module is good practice for development, but you don’t want to load many different JS files on your site in production. You can use a plugin like Autoptimize to automatically minify and concatenate your JS and CSS files to optimize your assets and improve your site load speed.

On this page