Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joseph-farruggio/6be24d6a8a1cc9e4f04fd6b6527f76a2 to your computer and use it in GitHub Desktop.
Save joseph-farruggio/6be24d6a8a1cc9e4f04fd6b6527f76a2 to your computer and use it in GitHub Desktop.

/* Form Validation Code */

Javascript form validation checks for values in the name and message input fields. Custom error labels are appended as friendly reminders that a value is required.

// Wait for the DOM to be ready
jQuery(document).ready(function( $ ) {
    // Require jQuery Validate plugin
    $("input").prop('required',true);
    $.getScript( 'https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js' ).done( function() {
    	// When user focuses and exits the input field
        $('input, textarea').on('change focus blur', function() {
            var $field = $(this)
	    // If there's a value, set the class
            if ($field.val()) {
              $field.addClass('has-value');
            } else {
              $field.removeClass('has-value');
            }
        }).change();
        
        // Validation with the jQuery Validate plugin
        $("form.wpcf7-form").validate({
            // target our fields by name
            rules: {
              "your-name": "required",
              "your-message": "required",
            },
            // Specify validation error messages
            messages: {
              "your-name": "Don't be shy. Introduce yourself with a name.",
              "your-message": "Have something to say? Be sure to leave us a message.",
        },
        // Make sure the form is submitted to the destination defined
        // in the "action" attribute of the form when valid
        submitHandler: function(form) {
          form.submit();
        }
      });
    });
});

We'll give the error labels a red theme to communicate that something is wrong. We'll make the red colors a little muted in effort to keep things warm and not too alarming. I'm also overriding WPCF7 styles to make the fields full width.

<style>
.wpcf7 label.error {
	padding: 2px 2px 2px 10px;
	background: rgba(255,0,0,.1);
	border-left: 4px solid;
	border-color: rgba(255,0,0,.6);
	color: #f00;
}
body .wpcf7 input.wpcf7-text, body .wpcf7 input.wpcf7-quiz, body .wpcf7 input.wpcf7-number, body .wpcf7 textarea.wpcf7-textarea { width: 100%; }
</style>

/* Form Restyling Code */

Since Contact Form 7 is dictating our markup and didn't provide us with input placeholders, we'll be making use of the label as the placeholder in order to achieve the design requirements.

  • We position the input field on top of label with a negative 'top' value
  • We set the z-index of the input field to minus 1 so that the label is visible as the top layer
  • We set css rules to raise the input field back to the top (hiding the label) when the user has focused (or clicked) the input to type
  • If the user exits focus without supplying a value, the label is back on top
  • If the user supplies a value and exits focus, a css class is applied to keep the label hidden
/* Swap the two columns */
.vc_custom_1502143926610 { float: right; }

/* Form Labels - style only the original children as to avoid styling error labels appended by jQuery Validation plugin */
.wpcf7-form p > label {
    position: relative;
    padding: 10px 0 0 10px;
    cursor: text;
}

/* Make the form label the first relative ancestor */
span.wpcf7-form-control-wrap { position: static; }

/* Position the input field right underneath the label */
.wpcf7-form-control {
    position: relative;
    top: -35px;
    left: -10px;
    z-index: -1;
    padding: 4px 6px 4px 9px;

}

span.wpcf7-form-control-wrap { height: 30px; }
    
/* Add height to textarea parent to make up for lost height */
span.wpcf7-form-control-wrap.your-message { height: 170px; }

/* Check if field has a value. If true, then hide label */
.wpcf7-form-control.has-value {
    z-index: 0;
}

.wpcf7 label.error {
	position: relative;
    top: -40px;
    left: -10px;
	margin-top: 5px;
	padding: 2px 2px 2px 10px;
	background: rgba(255,0,0,.1);
	border-left: 4px solid;
	border-color: rgba(255,0,0,.6);
	color: #f00;
}

/* Hide wpcf7 error if a custom one exists */
.error + .wpcf7-not-valid-tip {
    display: none;
}

/* On focus, reset the input's z-index so that the input is on top of the label */
input.wpcf7-form-control.wpcf7-text:focus { z-index: 0; }
textarea.wpcf7-form-control.wpcf7-textarea:focus { z-index: 0; }

/* Removing unnecessary padding after customizations */
.wpcf7 span { padding: 0; }

/* Override wpcf-7 to make all fields 100% width */
body .wpcf7 input.wpcf7-text, body .wpcf7 input.wpcf7-quiz, body .wpcf7 input.wpcf7-number, body .wpcf7 textarea.wpcf7-textarea { width: 100%; }

/* Submit button styles */
body .wpcf7 input.wpcf7-submit {
    width: initial;
    border: 2px solid;
    padding: 18px 30px;
    z-index: 2;
    float: right;
    top: 0;
}

/* Cookie Monster Code */

In the last exercise, we make use of 3 functions to achieve the desired behavior.

  1. On page load we check if the user has a cookie labeled "surefoot-friend" set with a value of 1.
  2. If the cookie is found, we replace the inner html of the div holding the contact form with the message and gif.
  3. We set the cookie for those who did not have it which expires in one year.
$(function(){
    // Set Cookie
    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+ d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }
   
   function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    
    function checkCookie() {
        var friend = getCookie("surefoot-friend");
        if (friend == 1) {
            document.getElementById('wpcf7-f949-p950-o1').innerHTML= `
                <div id="friendModal">
                    <p>Hmm, you look familiar. While you're waiting for our reply, here's a GIF we think you should see.</p>
                    <div style='width:100%;height:0;padding-bottom:56%;position:relative;'><iframe src='https://giphy.com/embed/SZUnyVdIDAEQU' width='100%' height='100%' style='position:absolute' frameBorder='0' class='giphy-embed' allowFullScreen></iframe></div>
                </div>
            `;
        }
    }
    
    checkCookie();
    setCookie('surefoot-friend', 1, 365);
   
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment