I have this JS that has a lot of redundant functionality, and it works but looks unseemly.
I would love some assistance with making this more DRY (Don't Repeat Yourself):
// This provides character & word counter functionality
counter = function() {
var body_value = $('#post_body').val();
var title_value = $('#post_title').val();
if (body_value.length == 0) {
$('#wordCountBody').html(0);
$('#totalCharsBody').html(0);
return;
}
if (title_value.length == 0) {
$('#wordCountTitle').html(0);
return;
}
var regex = /\s+/gi;
var wordCountBody = body_value.trim().replace(regex, ' ').split(' ').length;
var totalCharsBody = body_value.length;
var wordCountTitle = title_value.trim().replace(regex, ' ').split(' ').length;
$('#wordCountBody').html(wordCountBody);
$('#totalCharsBody').html(totalCharsBody);
$('#wordCountTitle').html(wordCountTitle);
};
$(document).ready(function() {
$('#count').click(counter);
$('#post_body').change(counter);
$('#post_body').keydown(counter);
$('#post_body').keypress(counter);
$('#post_body').keyup(counter);
$('#post_body').blur(counter);
$('#post_body').focus(counter);
$('#post_title').change(counter);
$('#post_title').keydown(counter);
$('#post_title').keypress(counter);
$('#post_title').keyup(counter);
$('#post_title').blur(counter);
$('#post_title').focus(counter);
});
this. Secondly,jQuery.onaccepts an object parameter for assigning handlers to multiple events. \$\endgroup\$readydeclared/assigned? \$\endgroup\$counter. I updated the question to include that code. It was irrelevant to this issue, so I left it out for brevity. \$\endgroup\$readyis irrelevant to the question, it's better to remove its usages not to add its declaration :-) \$\endgroup\$