Monday, 20 February 2012

Word count in Javascript

I notice the (current at time of writing) top Google results for word count in Javascript all offer something like:
function countWrong(textarea){
 var words=textarea.split(" ");
 alert(words.length+" words");
}
This is Wrong!


Why? Because  a space isn't the only thing that can separate words. If the user hits Return at the end of the word, this inserts a newline, which won't be counted as a word separator by the above code. And if the user adds commas or other punctuation  that is not followed by a space - or adds a comma with a space either side of it - then this will also result in an incorrect count.


Even worse, if the user has more than one space between words, or extra space at the end of the input, then this will up the word count making it even more inaccurate.


Fortunately there's an easy way to count words using regular expressions. A pattern of '\w+' will match a string of characters that can be in a word. With this technique, there's no need to worry about trimming the string to remove excess space, either.

So try this instead:


function wordCount(textarea){
 var chars=textarea.value.length,
 words=textarea.value.match(/\w+/g).length;
 alert(words+" words\n"+chars+" characters");
}


for a much more accurate result.

Friday, 13 January 2012

Search Engine Submission - only 2 required

"We will submit your website to hundreds of search engines!" sounds like a scam. It is. According to NetMarketShare, Google has 79% of the search market. In some countries it's a lot higher. Second is the Chinese search engine, Baidu on 11%. Then we have Yahoo on 6% and Bing on 3%. That adds up to 99% of the search engine market. The biggest player in the tiny bit remaining is Ask.

So, whilst it is true that there are hundreds of other search engines, virtually nobody is using them. OK, there's a few that may be be important in specific geographies - like Yandex in Russia, for example.

Yahoo search results are now supplied by Bing: if you can get listed in Bing, you will be listed in Yahoo. So to get 88% coverage - or more if you ignore the huge Chinese market - you just need to submit to Google and Bing.

If you don't want to ignore the huge Chinese market, Baidu has a submit page but when I recently created a brand new site the Baidu spider came to index it without any invitation from me, even though there were no other sites linking to it. I'm guessing it's somehow monitoring domain name registrations or DNS changes. All my older sites are listed, even though I've never done anything to submit pages to Baidu.

So how to get listed in Google? Sign up for Google Webmaster Tools and click the big red Add a Site link. To take full advantage of all the useful information that Webmaster Tools offers you will need to verify that you own the site. Google supplies a tiny XML file that you upload to your website and then you just tell Google it's there. It's all explained once you're registered.

To do the same for Bing (and therefore Yahoo) the process is virtually identical.  Sign up for Bing Webmaster Tools - name sound familiar? The Bing Add Site button is blue and Bing supplies a tiny XML file that you upload to your website and then you just tell Bing it's there. It's all explained once you're registered.

Now you should get spidered by the world's largest search engines and your fortune is made. Well maybe not, but you've certainly saved some money by not signing up for some "We will submit your website to thousands of search engines!" program.


Wednesday, 4 January 2012

Whizzywing has landed

Whizzywing is a new WYSIWYG editor, descended from Whizzywig but written anew in the age of HTML5. It has rethought the interface, putting the most common formatting in two dropdowns so that almost every format change can be done with a single click. It is very small - just 7k gzipped - but you can activate it without installing a single thing on your server as the code can be served from whizzywing.com. Just add
<script src="http://whizzywing.com/whizzywing.js"></script>
in the head section of your HTML and any element with a class="WYSIWYG" will be turned into a rich text editor. It's not limited to textareas. It's rich in features, too: correct me if I'm wrong but no other editor this small provides table editing. That's if there is another editor this small. With just 9 items on the toolbar you can do most of the formatting that you could do with CKEditor or TinyMCE but using a fraction of the bandwidth and without the installation headaches. It is easy to pick up and is more than powerful enough to use in a CMS.

Look carefully and you will see that network traffic is minimised by using no images on the toolbar - those little icons are all drawn using standard entities and CSS. It's faster even than using an image sprite. But everything is tailorable, so if you want to design your own icons, or use a a fancy set from elsewhere, you can add your own. Simple changes like excluding unwanted items from the toolbar can be done without using any javascript at all.

There has been a lot work under the bonnet to keep the generated HTML sane, no matter what browser you are using. There won't be a load of browser specific classes or deprecated font tags. Hit enter after a paragraph or a heading and you will get another paragraph - not a div, or orphaned text separated off with extra break tags. That means there won't be problems if you come back and edit the same text in a different browser.

The code is licenced under MIT and LGPL. You can download it, or create your own fork, at github. Try it at Whizzywing.


Friday, 16 December 2011

IOS5 now supports contenteditable. Come on Android!

Users who love or need their WYSIWYG editor (Whizzywig, TinyMCE, CKEditor etc.)  have been complaining for years that they would not work on on their mobile device. They could edit their blog or update their favourite site with rich text on their desktop machine but no joy on their iPad or smartphone.

They would not work because no mobile browser would support the contentEditable attribute despite the fact that all the major browsers support it in their desktop versions - Internet Explorer since 5.5. Well it seems Apple have been listening and now these things will work in IOS5. Great if you have an iPad 2.

Not so great with Android though, which not only still fails to support it, but actually lies if you test for support:


document.getElementById("test").isContentEditable


returns "true" but the onscreen keyboard will not appear so you cannot type into the edit area. This is Issue 8253 for Android. No sign of a fix yet.

Friday, 9 December 2011

Last Whizzywig of 2011

There's a new version of Whizzywig 2011  and it should be the last one ever. Clearly we can't go on calling new releases "2011", so in 2012 it will appear with a new name - how exciting! - and, if all goes according to plan, its own website.

Many thanks to all who have tried it out in 2011 and provided feedback. Hopefully it will be a much better editor for this.

The main new feature is clean pasting: if you paste in stuff from a document or a website then the editor will strip out all extraneous styling, fonts, colors , spans, classes and ids that only made sense on the original page, leaving you with some uncluttered and pure html. This should be pretty consistent across browsers (some were driving me mad with their silly paste behavior!).

And here, documented for the first time, are the keyboard controls:
 CTRL+Space - Clear all inline styles and classes
 CTRL+B - Bold selected text
 CTRL+I - Italic selected text
 CTRL+U - Underline selected text
 CTRL+H - Edit the HTML source
 CTRL+L - Insert a Link
 CTRL+M - Insert an iMage

Note that the cursor must be in the edit area for the above to work, or you'll get the browser default action (History, Bookmarks, etc.)

Double-click
 a link - bring up the Link dialogue
 an image - bring up the Image dialogue
 the toolbar - toggle full window

Friday, 23 September 2011

Really simple WYSIWYG, with jQuery

or, How to make a WYSIWYG input with Javascript

I've made a really simple WYSIWYG editor with jQuery to demonstrate how to use contenteditable with execCommand to format text.

It's not a plug-in and the main virtue of using jQuery for this demonstrator is that it makes the code easy to figure out. Have a look at the source and use it as a starter if you want to make your own editor. There's about 30 lines of HTML and another 30 or so of JavaScript.

The HTML consists of contenteditable div, editor, which is where the editing takes place and above it a div, toolbar,  containing controls - buttons and a select - to call up the commands to edit the text in  editor, plus a button to view the HTML source of the document in editor. This is all within a container div, WYSIWYG.

Then there is a textarea, HTML, which holds the HTML source for the document being edited. Above it is a button to return to the WYSIWG view. These are in a container div, source.

There's just 4 JavaScript functions: the first is a wrapper for execCommand:
function make(cmd,parm){

 if (cmd.indexOf('<')==0){
  parm=cmd;
  cmd="FormatBlock";
 }
 if (cmd == "InsertImage") parm = prompt("Filename or path to image","");
 if (cmd == "CreateLink") {
  parm = prompt("URL or address of link (leave blank to unlink)","http://");
  if (parm=="" || parm=="http://"){cmd="Unlink"}
 }
 try {document.execCommand(cmd,false,parm);} catch(e){alert(e)};
}


Then there's a function to show the WYSIWYG view and hide the Source view:

function vWhizz(){
 $('#source').hide();
 $('#WYSIWYG').show();
 $('#editor').html($('#html').val())
}


The last line of this copies the html inside the textarea into the editor.

Next, a function to hide the WYSIWYG and show the source in the textarea:

function vSource(){
 $('#html').val($('#editor').html());
 $('#WYSIWYG').hide();
 $('#source').show();
}


The first line of this copies the edited HTML back into the textarea.


Not strictly necessary, is a function to resize the editor/textarea so it fills to the bottom of the window:

function reHeight(){
 var top=Math.max($('#editor').offset().top,$('#html').offset().top),
 newHeight = $(window).height() - top - 10; 
 $('#html').css('height',newHeight+'px');
 $('#editor').css('height',newHeight+'px');
}



When the DOM is first loaded, we bind the reHeight function to a resize of the window,
show the WYSIWYG view and hide the source view:

$(document).ready(function() {
 $(window).resize(reHeight);
 make('styleWithCSS',false);
 vWhizz();
 reHeight()
});



"make('styleWithCSS',false);" is there just to stop Firefox and other Gecko-based browsers sticking in some in-line styles instead of using HTML for bold and italics.


See the HTML to see how the toolbar controls issue commands.


Maybe there will be a proper plug-in with more functionality along later.

Tuesday, 23 August 2011

CSS inline-block on IE6 and IE7

The CSS display property can be set to "inline-block":



inline-block
This value causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.


This is useful for all sorts of stuff including displaying inline a row of images and captions in the same block , or as a container for a dropdown menu. But older browsers, notably Firefox 2 and Internet Explorer 6 and 7, do not support it. See the Mozilla Webdev blog for an explanation and fix.

In summary you can add "zoom:1; *display:inline" to trigger haslayout for IE  and exploit the "*" CSS hack to make the thing inline.

But if you look at Quirksmode's always helpful compatibility page, you'll see that "IE 6/7 accepts the value only on elements with a natural display: inline."

So if you are not worried about Firefox 2 (anyone still using that? why?)  you can simply make the inline-block container a span instead of a div and not worry about any hacks for Internet Explorer.

The trouble with hacks is you can never be sure they are proof against future browser releases.