I have a page textbox that a user can type in. As the user types, I want to highlight sections of text. To keep things simple, I'm just trying to highlight all vowels at the moment.
The first part of the code is from this question:
$('[contenteditable]').live('focus', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).live('blur keyup paste', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
From which I can then write this:
var magicRegex = /[aeiou]/gi;
$('#message').change(function() {
$(this).find('br').replaceWith('\n');
var message = $(this).text();
message = message.replace(magicRegex , '<mark>$&</mark>');
message = message.replace(/\n/gi, '<br />');
$(this).html(message);
}).change();
This code highlights vowels as the user types. However, in doing so, the focus on the field is lost every time the highlighting updates, and the user must click again to type another character.
How can I fix this?