Skip to Content

cf7LocalStorage()

Utilize localstorage on Contact Form 7 text inputs to make it easier for users to continue filling out previously abandoned forms on future visits.

JavaScript February 19, 2018

Usage

This function runs automatically, so it is not called manually. Is this incorrect?

Source File

Located in /assets/js/nebula.js on line 2648.

JavaScript
nebula.cf7LocalStorage = function(){
    if ( !jQuery('.wpcf7-form').length || jQuery('.ie, .internet_explorer').length ){
        return false;
    }

    jQuery('.wpcf7-textarea, .wpcf7-text').each(function(){
        var thisLocalStorageVal = localStorage.getItem('cf7_' + jQuery(this).attr('name'));

        //Fill textareas with localstorage data on load
        if ( !jQuery(this).hasClass('do-not-store') && !jQuery(this).hasClass('.wpcf7-captchar') && thisLocalStorageVal && thisLocalStorageVal !== 'undefined' && thisLocalStorageVal !== '' ){
            if ( jQuery(this).val() === '' ){ //Don't overwrite a field that already has text in it!
                jQuery(this).val(thisLocalStorageVal).trigger('keyup');
            }
            jQuery(this).blur();
        } else {
            localStorage.removeItem('cf7_' + jQuery(this).attr('name')); //Remove localstorage if it is undefined or inelligible
        }

        //Update localstorage data
        jQuery(this).on('keyup blur', function(){
            if ( !jQuery(this).hasClass('do-not-store') && !jQuery(this).hasClass('.wpcf7-captchar') ){
                localStorage.setItem('cf7_' + jQuery(this).attr('name'), jQuery(this).val());
            }
        });
    });

    //Update matching form fields on other windows/tabs
    nebula.dom.window.on('storage', function(e){ //This causes an infinite loop in IE11
        jQuery('.wpcf7-textarea, .wpcf7-text').each(function(){
            if ( !jQuery(this).hasClass('do-not-store') && !jQuery(this).hasClass('.wpcf7-captchar') ){
                jQuery(this).val(localStorage.getItem('cf7_' + jQuery(this).attr('name'))).trigger('keyup');
            }
        });
    });

    //Clear localstorage when AJAX submit fails (but submit still succeeds)
    if ( window.location.hash.indexOf('wpcf7') > 0 ){
        if ( jQuery(window.location.hash + ' .wpcf7-mail-sent-ok').length ){
             jQuery(window.location.hash + ' .wpcf7-textarea, ' + window.location.hash + ' .wpcf7-text').each(function(){
                localStorage.removeItem('cf7_' + jQuery(this).attr('name'));
                jQuery(this).val('').trigger('keyup');
            });
        }
    }
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.cf7LocalStorage = function(){
    //Write your own code here, leave it blank, or return false.
}