Adding Custom Javascript Only When a Specific Block is Present

– an exercise in block customisation

This post is part of a series exploring how to customise a core block in the WordPress Block Editor. Our example is aiming to offer the option of a “true parallax” effect on the Block Editor Cover Block.


Adding Custom Javascript Only When a Specific Block is Present

Example of Cover Block with “True Parallax”

Parallax for the Cover Block

We need to add a small Javascript file, to enable the parallax effect. When a cover block on the page has a class of “is-style-true-parallax”, the parallax Javascript will take effect.

For all of the customisation options explored (with the exception of creating an entirely new block), this Javascript is added in the same way. It is added to the front end only (so the effect is not visible in the editor) and is added only if the Cover block is present on the page.

The following code is added to functions.php in the theme, or in a plugin file (with appropriate changes to file location):-

// Enqueue the parallax js if the cover block is included on the page
function webl_enqueue_if_block_is_present(){
    if ( has_block( 'core/cover' ) ) {
        wp_enqueue_script(
            'true-px',
            get_stylesheet_directory_uri() . '/assets/js/true-bg-parallax.min.js',
            array(),
            '1.0.0',
            true
        );
    }
}
add_action( 'enqueue_block_assets', 'webl_enqueue_if_block_is_present' );

Note: these code snippets are for use within a theme. This code could equally be used in a plugin after modifying the file locations, by using plugin_dir_url() for example.

Read about Adding a Custom Block Style to the Cover block to add a class activate the parallax effect.