questions

WordPress – .js file loads but does nothing

Rate this post

I’ve made a form and a validation function that goes with it. I enqueued the javascript in the function.php and it gets loaded. The only page that I want this .js to be run on is reservation.php so I’ve added if ( is_page_template( 'reservation.php ) ). I have also enqueued some jquery that way which also gets loaded but that actually works.

The problem is that none of my .js functions are working.

For example amongst them I have an onblur function which does not trigger.

If I look at the Network tab in F12 tools, I can see that the formValidator.js was loaded, and it has status 200.

Any help would be welcome. If I can provide any additional information, feel free to ask.

Thank you.

function wpse_enqueue_form_validation_script(){
    if ( is_page_template( 'reservation.php' ) ) {
        wp_enqueue_script('formValidator', get_template_directory_uri() . '/js/formValidator.js');
    }
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_form_validation_script' );

 

✔️Solution:

I imagine you are attempting to run a script that references a node that doesn’t yet exist in the DOM.

Try enqueuing your script in the footer:

wp_enqueue_script( 'formValidator', get_template_directory_uri() . '/js/formValidator.js', array('jquery'), false, true );

// Pass true for the 5th parameter to print the <script> tag at the bottom of <body> instead of inside <head>      ^^^^

Which ensures your script doesn’t get executed until the entire DOM has been loaded.

Alternatively, in your JavaScript, wait for the DOM to be ready by wrapping your code in a $(document).ready jQuery handler:

$(function(){
    // Dom is ready for selection
});

Leave a Reply

Your email address will not be published.

Back to top button