Created
December 16, 2016 18:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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;"> 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