Giulio Bonanome Giulio Bonanome - 6 months ago 20
Javascript Question

Resolve javascript conflict with parent theme on wordpress child theme

I've built a child theme of Divi Theme to use with Buddypress. So far so good, except for a script conflict on commenting buttons.

The theme load a javascript (

js/custom.js
at 2642:2662) with the following function:

$( 'a[href*=#]:not([href=#])' ).click( function() {
if ( $(this).closest( '.woocommerce-tabs' ).length && $(this).closest( '.tabs' ).length ) {
return false;
}

if ( location.pathname.replace( /^\//,'' ) == this.pathname.replace( /^\//,'' ) && location.hostname == this.hostname ) {
var target = $( this.hash );
target = target.length ? target : $( '[name=' + this.hash.slice(1) +']' );
if ( target.length ) {
et_pb_smooth_scroll( target, false, 800 );

if ( ! $( '#main-header' ).hasClass( 'et-fixed-header' ) && $( 'body' ).hasClass( 'et_fixed_nav' ) && $( window ).width() > 980 ) {
setTimeout(function(){
et_pb_smooth_scroll( target, false, 200);
}, 500 );
}

return false;
}
}
});


This event target the same button that Buddypress use for commenting, preventing AJAX form from loading on click.

enter image description here

I don't want to edit the parent theme (custom.js). How can I prevent this conflict? Is there a workaround, maybe from functions.php?

UPDATE

Using [wp_dequeue_script][4] to load that script later, didn't work. When using this code in functions.php

function de_script() {
wp_dequeue_script( 'divi-custom-script' );
}
add_action( 'wp_print_scripts', 'de_script', 100 );


then the full script (custom.js) was not loaded at all.

Answer

First of all, to resolve the javascript conflict I've set up a simple tl_custom.js under my theme js/ folder, with the following code

jQuery(document).ready(function($) {
    //  Remove handler set by themes/Divi/js/custom.js at line 2642
    $( 'a[href*=#]:not([href=#])' ).off();
});

Then I add the script with the following code in functions.php

function tl_custom_scripts() {
    if ( ! is_admin() ) {
        $scriptsrc = get_stylesheet_directory_uri() . '/js/';
        wp_register_script( 'tl_custom', $scriptsrc . 'tl_custom.js', '', '', true );
        wp_enqueue_script( 'tl_custom' );
    }
}
add_action( 'wp_enqueue_scripts', 'tl_custom_scripts', 20 );

The main problem is that the parent theme register custom.js in the footer, so I had to set the wp_register_script last parameter to true and then set add_action priority to 20.

Comments