Thursday, 28 June 2012

Setting a focus and blur event for TinyMCE

I've been very busy because of work, working out and other things, and have therefore not really been able to update this blog, but I'll be sure to try and update the blog more often. I'll probably end up importing the contents into a WordPress installation on my server.

Outside the usual life stuff, I've been working on a new project with a friend, and should hopefully be on line in about a week. With this project we needed some sort of input of course, one of those (the biggest one) was an text area, however, I wanted to allow users some basic mark up,  name, bold, italic and underline. While there were many ways of implementing this, I thought the best way was to implement a WYSIWYG that would allow only those mark ups, and TinyMCE is one of the best.

I’ve never really worked with any WYSIWYG editors, and I needed to customise this to only allow the HTML tags strong, b, em, i, and u. All this should not have any attributes. The editor would not have any toolbars and whatnot, which meant creating a custom theme. This was fairly easy by stripping apart the simple theme. None of this was the real challenge though.

It seemed that there was no “proper” way of doing an event handler for focus and blur that would work in a cross browser environment. There wasn’t much online to help this, bits and pieces everywhere, but no definitive answer. So I am here to share with you the definitive answer!

You need to add an onInit function and add a blur/focus event properly; however, the element needs some checking. The element and the whole setup function are as follows:

Highlighted using GeSHi
  1. setup : function(ed) {
  2.     ed.onInit.add(function(ed) {
  3.         var dom = ed.dom,
  4.             doc = ed.getDoc(),
  5.             el = doc.content_editable ? ed.getBody() : (tinymce.isGecko ? doc : ed.getWin());
  6.         tinymce.dom.Event.add(el, 'blur', function(e) {
  7.             console.log('blur');
  8.         })
  9.         tinymce.dom.Event.add(el, 'focus', function(e) {
  10.             console.log('focus');
  11.         })
  12.     });
  13. }

The trick, as most of you JS heads will have seen, is the variable el. Where it checks if TinyMCE used content_editable, in which case it gets the TinyMCE body, otherwise it checks if it’s a Gecko engine, in which case it gets the document, and finally if none of those, it gets the document window.

Hope that helps you out! :)

No comments:

Post a Comment