I have a textfield in which I'm writing some text.
For the sake of simplicity, I want that alert('Boom!')
jumps out every time I start writing in between two $$.
For example I have a blank textfield and start typing (cursor is "|" sign)
Today is a really nice day|
nothing happens, start typing
Today is a really nice day, $|$
still nothing, but now when I start typing
Today is a really nice day, $someText|$
alert box should jump out for each letter in between those dollar signs.
Why do I need that kind of feature? I want live-equation-preview (MathJax rendering) every time user starts typing his/her equation, and I can recognize it's an equation by $$ signs (everything in between is rendered).
EDIT: Multiple $$'s are possible in textfield. Script must recognize the one which is currently active (cursor position is between it's $$'s).
You can use jQuery caret plugin
http://examplet.buss.hk/download/download.php?plugin=caret.1.01
note: edit and delete these characters Ôªø from line 8
and replace
funcition. ( not to replace anything but to use the index of matched pattern )
$("#myText").bind("keyup", function(e){
var text = $(this).val();
var caret = $(this).caret().start;
if(text && text.length > 0){
text.replace(/\$.*?\$/g, function(m, n){
if(caret > n && caret < (n + m.length)){
alert("BOOM");
}
});
}
});
demo : http://jsfiddle.net/xqXXb/
Just showing how to do it. You can improve this.
use
$("#myText").bind("keyup keydown change", function(e){ ...
for a better result.