Fixing a JavaScript conflict between the parent theme and the child theme in WordPress

Recently, I created a customized child theme based on the Divi Theme, tailor-made for integration with Buddypress. Everything was going smoothly until I encountered a conflict involving the commenting buttons due to a script.

In my theme, there is a JavaScript file (js/custom.js) that contains 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 function happens to affect the same button used by Buddypress for commenting, thereby hindering the AJAX form from loading when clicked.

I am reluctant to modify the parent theme's script (custom.js). Is there a way to resolve this conflict without editing the main script? Perhaps through some workaround in functions.php?

UPDATE

Even after attempting to delay the loading of the script using [wp_dequeue_script][4] in functions.php, it did not yield the desired outcome. The code snippet utilized was as follows:

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

Unfortunately, this action resulted in the complete non-loading of the entire script (custom.js).

Answer №1

To address the JavaScript conflict, I took the initiative to create a basic tl_custom.js file within the js/ directory of my theme.

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

Next, I included this script in the backend by adding the following code snippet to the functions.php file:

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 );

An issue arose due to the parent theme registering the custom.js in the footer. To overcome this, I set the last parameter of wp_register_script to true and adjusted the priority of the add_action function to 20.

Answer №2

Although I may be chiming in a bit late, I have recently taken over a project that was passed down to me. Upon further examination, I discovered that the previous developers had utilized a Divi theme on a WordPress site, leading to the manifestation of multiple errors.

Upon inspecting the source code, I pinpointed an incorrect selector:

$( 'a[href*=#]:not([href=#])' )

To rectify this issue without impacting any functionalities, I made the following adjustment:

$( 'a[href*=\\#]:not([href=\\#])' )

Alternatively, the problem can also be resolved with:

$( 'a[href*="#"]:not([href="#"])' )

After implementing these changes, the error was resolved and the functionality of the affected code block remained intact.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking for a streamlined method to simultaneously access multiple APIs with GraphQL and React

For my client side project, I'm using GraphQL and React but opting not to use Redux for state management. Instead, I have organized my API calls into custom hook files as shown below: const [getSomeData, { data: getSomeDataData, loading: getSomeData ...

Using ngModel to retrieve and display only the month, year, and date

Currently, I am working with an interface named Person which includes fields such as name, last name, birthday, and others. However, I am facing a confusion when it comes to the person's birthday format, as it contains some additional letters at the e ...

Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;? However, if I use bracket notation like return contacts[i][prop];, it works fine an ...

What is the best way to transfer values from an AJAX script to the rest of the Javascript code?

Currently, I am diving into the world of a django 2.0 template along with a third-party jQuery script used for tagging photos and my own JavaScript code that acts as the "glue." Despite being new to JavaScript and JQuery, I managed to make a successful aja ...

Toggle the visibility of a table column based on user selection in Vue.js

I am having issues with displaying and hiding based on checkbox click events. Can anyone assist in identifying the mistake? When clicking on an ID, it should hide the ID column. Similarly, clicking on "first" should show/hide based on checkbox clicks, and ...

Encountering authentication issues with Kohana/PHP when making an AJAX request

In my project, I have a base class that serves as the parent for all controllers. This base class contains a function to determine the role of the logged-in user using the Auth library. Upon determining the user's role, a variable $LoggedIn_role is as ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Using ASP.NET MVC 6 Web API along with Angular, a resource can be posted as an object property in the

I am facing a challenge in sending a complex object from Angular to my web API. Here is how the object looks: { Name: "test", Tax: 23, Addresses: [ { country: "ro", city: "bucharest" }, { country: "fr", ...

Sequelize Error: The WHERE parameter for 'email' is throwing an error due to an invalid value of 'undefined'

Currently, as part of my Node.js application, I am using Sequelize to develop a user registration feature. However, I seem to be facing an issue when attempting to verify the existence of a user based on their email address. The error that keeps popping up ...

Using JavaScript's setInterval function in conjunction with Math.random to obtain a random value

Just generated some random numbers. Wondering how to dynamically update the values of these numbers every 5 seconds with fluctuations less than +/- 5% compared to the current value. Need help using the setInterval function. Here is my code for Random Pric ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...

Exploring the issue of why the scroll event handler is not functioning properly within the useEffect hook

After creating a custom hook to retrieve the scroll state of an element, I noticed that the scrollHandler only triggers once. Here's my code: import { MutableRefObject, useEffect, useState } from "react" export const useScrollState = <TE ...

Encoding JSON and parsing data in case no results are retrieved

I am working on an AJAX project using PHP and JQuery, but I have encountered a problem. Specifically, I am facing an issue related to the dataType:"json" parameter in my Javascript code. Everything runs smoothly when the json_encode function returns rec ...

Access the angular controller using the radio button option

I am looking to showcase data in an HTML table retrieved from an Angular controller. I have the controller set up but I am unsure about how to display the data when a radio button is selected. <div class="radio"> <label class="radio-inline" ...

Encountering a 404 error when attempting to access static files within a directory using Express Js

Organizing my static files has been a breeze with multiple directories. I have some static files in the client directory, while dashboard-related files are nested within the src directory. Here is how my directory structure looks: / | client //housing sta ...

Wordpress Issues with Displaying Arabic Text Correctly

The issue arises when displaying Arabic text in menus, both the top menu and main menu. The text appears distorted and unreadable, with characters like 2Ø®Ø§Ù†Ù‚Ø§Û showing up. However, in other areas of the page such as the body content, the ...

($rootScope: busy) Applying changes right now

Whenever I try to make changes to the UI grid after refreshing the data, I keep encountering this error message: angular.js:13236 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24apply ...

Connect a parent node to a specific subset within Mermaid's graph structure

Managing a complex Mermaid diagram that includes numerous subgraphs can be challenging. The size of the diagram often makes it difficult to maintain the correct order of subgraphs, leading to occasional rearrangements for clarity and positioning. However, ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

Establishing the maximum width of a Vuetify expansion panel component

I'm currently in the process of developing a webpage using vuetify and nuxt. My main focus right now is adjusting the max-width property of the expansion panel UI component (https://vuetifyjs.com/en/components/expansion-panels). Here's the code s ...