Skip to content

Instantly share code, notes, and snippets.

@dhaupin
Created December 16, 2016 18:50
Show Gist options
  • Save dhaupin/b3812bf6e57c538259a036aac13d9495 to your computer and use it in GitHub Desktop.
Save dhaupin/b3812bf6e57c538259a036aac13d9495 to your computer and use it in GitHub Desktop.
Function - SEO - Look at input fields and display their current length as well as current cursor position
// Field needs data attrb like: <input name="title" data-seo-length="70" />
// Underscore library required for _.debounce() function
// https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js
<script type="text/javascript">
var count_name = $('input[name="title"]'),
stg_name = '<br/><div style="font-family:arial;font-style:italic;margin-top:5px;color:#969696;">&nbsp;&nbsp;SEO Chars: <span class="stg_name">' + count_name.val().length + '</span> of ' + count_name.attr('data-seo-length') + '. <span class="stg_name_cur">Cursor: 0</span></div>';
count_name.after(stg_name).on('keyup mouseup mouseleave', _.debounce(function(){
$('.stg_name').html($(this).val().length);
$('.stg_name_cur').html(caretPosition(count_name));
}, 200));
function caretPosition(input) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
diff = end - start;
if (start >= 0 && start == end) {
return 'Cursor: ' + start;
} else if (start >= 0) {
return 'Cursor: ' + start + ' to ' + end + ' (' + diff + ' selected)';
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment