FiddlingAway
FiddlingAway

Reputation: 2255

Custom JavaScript in WordPress Contact Form 7 not working

I'm trying to hide the contact form after it passes validation and is submitted. I want to do this with a simple custom JavaScript function.

The thing is, the console keeps informing me that my JS function is undefined. At first I had thought that this might be happening because I'm not enqueing the *.js correctly, but that's not the case - my custom.js is clearly visible in the page's source code, and its contents match what I'd put inside.

Here's my code so far.

functions.php (child theme)

add_action( 'wp_enqueue_scripts', 'for_contact' );
function for_contact() {
    wp_enqueue_script(
        'contactFormHide',
        get_stylesheet_directory_uri() . '/custom.js',
        array('jquery')
    );
}

custom.js

var $j = jQuery.noConflict();

$j(document).ready(function() {
    "use strict";

    function contactFormHide (){
        $('.section_inner_margin').css('display','none');
        $('.section_inner').html('<div class="wpcf7-response-output wpcf7-display-none wpcf7-mail-sent-ok" style="display: block;" role="alert">Your message has been sent.</div>');
    }

});

Contact Form 7 settings (Additional Settings tab)

on_sent_ok: "contactFormHide()"

What am I doing wrong, and how can I correct it?

Upvotes: 0

Views: 2524

Answers (2)

Ahmed Ginani
Ahmed Ginani

Reputation: 6650

Correction in the code. Define $ in the function.

var $ = jQuery.noConflict();

function contactFormHide(){
            $('.section_inner_margin').css('display','none');
            $('.section_inner').html('<div class="wpcf7-response-output wpcf7-display-none wpcf7-mail-sent-ok" style="display: block;" role="alert">Your message has been sent.</div>');
        }

Upvotes: 1

David Wilkinson
David Wilkinson

Reputation: 5118

Ahmed Ginani's solution will likely work but have you also tried passing $ as a parameter within a completely self-contained function as follows:

(function($) {
    $(document).ready(function() {
        "use strict";

        function contactFormHide (){
            $('.section_inner_margin').css('display','none');
            $('.section_inner').html('<div class="wpcf7-response-output wpcf7-display-none wpcf7-mail-sent-ok" style="display: block;" role="alert">Your message has been sent.</div>');
        }
    });
})(jQuery);

This way, you're passing the jQuery object as an argument to the function. This means we can use $ locally within the function without it conflicting with other scripts / frameworks / libraries, etc...

Upvotes: 1

Related Questions