Count the number of words of a Drupal node on double click with JQuery

Estimated reading time of this article: 0 minutes 44 seconds

Do you want to count your words in a node in Drupal 7?

Then create a wordcounter.js in your theme directory with following content:

// Adds Word counter for the node content
(function ($) {
  Drupal.behaviors.bodycountnode = {
    attach: function (context, settings) {
      $('.node .content .field-name-body', context).dblclick(function (event) {
        // replace(/></ig, '> <') is necessary in order to workaround block tag problems, e.g. <p>X</p><p>Y</p>.
        // Without the replace() we would get one word XY instead of X Y.
        var words = jQuery.trim(jQuery(this).html(jQuery(this).html().replace(/></ig, '> <')).text()).split(/\s+/).length;
        alert(words + " word(s)");
      });
    }
  };
})(jQuery);

And write in your template.php:

<?php
function YOUR_THEME_preprocess_node(&$variables) {
 
// Add a word counter for admins
 
if ($variables['is_admin']) {
   
drupal_add_js(path_to_theme() . '/wordcounter.js');
  }
}
?>

Note: The double click does not work in the overlay. It might be a problem in the Drupal overlay system.