Auto-focus Ajax
Auto-focus input field after successfully loading AJAX request.
by Jose SAYAGO
HTML
<div class="document">
<div class="objectWrapper">Ajax response here</div>
<div class="scan">
<textarea class="scanner" placeholder="Barcode"></textarea>
<button>Scan</button>
</div>
</div>
CSS
.document {
border: 1px solid #ccc;
background: #efefef;
}
.objectWrapper {
width: 73%;
background: #dfdfdf;
display: inline-block;
min-height: 200px;
padding: .5em;
border: 1px solid #efefef;
}
.scan {
width: 20%;
display: inline-block;
vertical-align: top;
}
textarea,
button {
width: 100%;
display: block;
border: 1px solid #afafaf;
background: #eee;
}
JavaScript
$(function() {
// Focus on load
$('.scanner').focus();
// Force focus
$('.scanner').focusout(function(){
$('.scanner').focus();
});
// Ajax Stuff
$('.scanner').change(function() {
$.ajax({
async: true,
cache: false,
type: 'post',
url: '/echo/html/',
data: {
html: '<p>This is your object successfully loaded here.</p>'
},
dataType: 'html',
beforeSend: function() {
window.alert('Scanning code');
},
success: function(data) {
window.alert('Success');
$('.objectWrapper').append(data);
},
// Focus
complete: function() {
$('.scanner').val('').focus();
}
});
});
});