Show Error Message on Focus

Input field will outline red on an error. At that point when the input gets focus an error message will appear.

by Travis Almand

HTML

<p>Type 'error' inside an input box and tab/click out of the input to trigger the error.</p>
<p>Click back into an input showing an error to see the message.</p>
<p>Remove 'error' and tab/click out of the input to hide message.</p>
<div class='input-block'>
    <input placeholder='Enter' class='answer' value='' />
    <div class='error-block'>
        <div class='error-text'>This is an error message.</div>
    </div>
</div>
<div class='input-block'>
    <input placeholder='Enter' class='answer' value='' />
    <div class='error-block'>
        <div class='error-text'>This is an error message.</div>
    </div>
</div>

CSS

.answer {
    border: 1px solid gainsboro;
    display: block;
    margin: 10px 0 0;
    outline: none;
    padding: 5px;
}
.error {
    border: 1px solid #BF262B;
}
.error-block {
    opacity: 0;
    overflow: hidden;
    height: 0;
    -webkit-transform: scaleY(0);
    transform: scaleY(0);
    -webkit-transform-origin: top left;
    transform-origin: top left;
    -webkit-transition: all 0.5s cubic-bezier(.17,.67,.58,1.46) ;
    transition: all 0.5s cubic-bezier(.17,.67,.58,1.46) ;
}
.error-text {
    background-color: #BF262B;
    color: white;
    margin-top: 10px;
    padding: 5px;
    position: relative;
}
.error-text:before {
    width: 0px;
    height: 0px;
    border-width: 0px 5px 9px;
    border-color: transparent transparent #BF262B;
    content: "";
    display: block;
    bottom: 100%;
    position: absolute;
    left: 10px;
    border-style: solid;
}

.error-block.show {
    opacity: 1;
    -webkit-transform: scaleY(1);
    transform: scaleY(1);
}

JavaScript

$('.answer').on('blur', function () {
    var $this = $(this);
    var $errorBlock = $this.next('.error-block');
    
    if ($this.val() === 'error') {
        $this.addClass('error');
    } else {
        $this.removeClass('error');
        $errorBlock.removeClass('show').height(0);
    }
}).on('focus', function () {
    var $this = $(this);
    var $errorBlock = $this.next('.error-block');
    var $errorText = $errorBlock.find('.error-text');
    
    if ($(this).hasClass('error')) {
        $errorBlock.addClass('show').height($errorText.outerHeight(true));
    }
});