Skip to content

Instantly share code, notes, and snippets.

@rdobrynin
Created February 16, 2016 13:41
Show Gist options
  • Save rdobrynin/a132f2296123ef2e64ac to your computer and use it in GitHub Desktop.
Save rdobrynin/a132f2296123ef2e64ac to your computer and use it in GitHub Desktop.

Revisions

  1. rdobrynin created this gist Feb 16, 2016.
    48 changes: 48 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    function replaceBubbleFormUI( form ) {
    // Suppress the default bubbles
    form.addEventListener( "invalid", function( event ) {
    event.preventDefault();
    }, true );

    // Support Safari, iOS Safari, and the Android browser—each of which do not prevent
    // form submissions by default
    form.addEventListener( "submit", function( event ) {
    if ( !this.checkValidity() ) {

    event.preventDefault();
    }
    });

    var submitButton = form.querySelector( "button:not([type=button]), input[type=submit]" );
    submitButton.addEventListener( "click", function( event ) {
    var invalidFields = form.querySelectorAll( ":invalid" ),
    errorMessages = form.querySelectorAll( ".error-message" ),
    parent;

    // Remove any existing messages
    for ( var i = 0; i < errorMessages.length; i++ ) {
    errorMessages[ i ].parentNode.removeChild( errorMessages[ i ] );
    }

    for ( var i = 0; i < invalidFields.length; i++ ) {
    parent = invalidFields[ i ].parentNode;
    parent.insertAdjacentHTML( "beforeend", "<div class='error-message'>" +
    invalidFields[ i ].validationMessage +
    "</div>" );
    }

    // If there are errors, give focus to the first invalid field
    if ( invalidFields.length > 0 ) {
    if($('#profile-info-form').length > 0) {
    $('html, body').animate({scrollTop : 0},800);
    }
    invalidFields[ 0 ].focus();
    }
    });
    }

    // Replace the validation UI for all forms
    var forms = document.querySelectorAll( "form" );
    for ( var i = 0; i < forms.length; i++ ) {
    replaceBubbleFormUI( forms[ i ] );
    }