Adding javascript actions to words in post content

Let’s assume you have a javascript like this:

function clickedTag( tag ) {
  var d = new Date(); 
  console.log( 'A word with tag ' + tag + 'has been cliked at ' + d.toDateString() );
}

And in your post you have this sentence:

The quick brown fox jumps over the lazy dog

And you want that the javascript clickedTag( "pet" ); will run when users click the word “dog”.

Probably the right approach on javascript side is write a single function with help of data attributes, something like:

The quick brown fox jumps over the lazy <span class="click-tag" data-tag="pet">dog</span>

and the javascript:

jQuery(document).on( 'click', 'span.click-tag', function(e) {
  e.preventDefault();
  var tag = jQuery(this).data('tag');
  if ( typeof tag === 'string' && tag !== '' ) {
    return clickedTag( jQuery(this).data('tag') );
  }
});

So, using a single tiny function you are able to run your javascript function with any word, and the word itself is not related to the parameter passed to function.

So far, so good. However this has nothing to do with WordPress, and yes, adding that tag to post content brings some problems you explained in OP and also manually adding the span code for every word where you need can be hard if you have a lot of posts and a lot of words that needs to be “tagged”.

But, yes, shortcodes can be a solution.

Just take one of the examples in the add_shortcode docs in Codex and modify it a bit:

function my_first_shortcode( $atts, $word='' ) {
  $atts = shortcode_atts( array ( 'tag' => '' ), $atts );
  $format="<span class="click-tag" data-tag="%s">" . esc_html( $word ) . '</span>';
  return sprintf( $format, esc_attr( $atts['tag'] ) );
}

add_shortcode( 'clicktag', 'my_first_shortcode' );

Once you have this few lines of PHP in your functions.php or in a plugin file, you will able to use the shortcode ‘clicktag’ in your posts, e.g. you can write

The quick brown fox jumps over the lazy [clicktag tag=”pet”]dog[/clicktag]

and the span with the data attribute will wrap the word “dog” in your post.

Combine that with the jQuery function posted above and you are done.

Note that the javascript I posted and also your javascript code (the function clickedTag in this example) should be enqueued in the pages using wp_enqueue_script.
A convenient way is to call wp_enqueue_script inside the shortcode callback (my_first_shortcode PHP function, in example above).

Finally, you would probably want to use the class ‘click-tag’ to style the span, and let users understand they are clickable.

In this Gist you’ll find a working, ready-to-install plugin (just download the 2 files and put them in a folder inside your plugin folder) that contains a just a little modified version of code I posted here.

Only thing left to do is write the real javascript code for clickedTag function, but that will not be covered here.