Adding a character counter to the excerpt metabox

Ok, so I didn’t like the way that was written, so i slightly rewrote it with different syntax, and more readable structure.

<?php 
// Add Character Counter to the Excerpt Meta Box
function excerpt_count_js(){
    if ('page' != get_post_type()) { ?>
        <script>

        (function($){

            $(document).ready(function(){

                if ( $('#postexcerpt').length ) {

                    var maxChar = 128;

                    $excerpt = $('#excerpt');

                    $("#postexcerpt .handlediv").after( '<div style="position:absolute;top:5px;right:80px;color:#666;">' +
                                                            '<small>Excerpt length: </small>' +
                                                            '<input type="text" value="0" maxlength="3" size="3" id="excerpt_counter" readonly="" style="background:#fff;" /> ' +
                                                            '<small>character(s). (' + maxChar + ' Characters MAX)</small>' +
                                                        '</div>'
                                                    );

                    $excerptCounter = $("#excerpt_counter");

                    $excerptCounter.val( $excerpt.val().length );

                    $excerpt.keyup( function() {

                        $excerptCounter.val( $excerpt.val().length );

                        var exColor = ( ( $excerptCounter.val() > maxChar ) ? 'red' : 'green' );

                        $excerptCounter.css( 'color', exColor );

                    });

                }

            });

         })(jQuery);

        </script>
    <?php }
}
add_action( 'admin_head-post.php', 'excerpt_count_js');
add_action( 'admin_head-post-new.php', 'excerpt_count_js');
?>

It didn’t have a check for whether or not #postexcerpt was even on the page, so I added that, and attempted to clean it up and make it easier to understand and change. I’m not a fan of the inline styling, but oh well.

Anyway, I tested this on a clean 4.6.1 install with 2016 installed, and it worked just fine. Let me know if this doesn’t work for you.