Ok:
Code:
function moveBold(el){
//Declare variables, especially determine the postion of the
//bold tag while defining c as the previous char #
var t=el.innerHTML, c=t.indexOf('<')-1, new_t='';
if(c<0) //if no bold tag, start from the end of the text
c=t.length-1;
t=t.replace(/<[bB]>|<\/[bB]>/g, ''); //remove existing bold tag
while(/[ \.,]/.test(t.charAt(c))) //skip spaces periods and commas by -
c--; // decrementing the character number for the char next in line
for (var i_tem = 0; i_tem < t.length; i_tem++) //loop the text one char at a time
if([i_tem]==c) //if the char is next in line -
new_t+='<b>'+t.charAt(c)+'<\/b>'; //enclose it in the new bold tag
else
new_t+=t.charAt(i_tem); //otherwise just use it 'as is'
el.innerHTML=new_t; //set the tag's innerHTML to the new string
if(!/<[bB]>/.test(new_t)) //if no bold tag -
moveBold(el); //do it again
}
document.onkeydown=function(e){ //assign document-wide event for keydown
var e=e? e : window.event; //determines the event object across browsers
if(e.keyCode==37) //check its key code, if it is the left arrow -
moveBold(document.getElementById('mb')); //run the function on the tag
}
Also, since you like it. Here is a version of it without any or (very little) global level exposure, one minor efficiency, and the 'play nice' feature I mentioned before:
Code:
<script type="text/javascript">
(function(){
function moveBold(el){
var t=el.innerHTML, c=t.indexOf('<')-1, new_t='';
t=t.replace(/<[bB]>|<\/[bB]>/g, '');
if(c<0)
c=t.length-1;
while(/[ \.,]/.test(t.charAt(c))){
c--;
if(c<0)
c=t.length-1;
}
for (var i_tem = 0; i_tem < t.length; i_tem++)
if([i_tem]==c)
new_t+='<b>'+t.charAt(c)+'<\/b>';
else
new_t+=t.charAt(i_tem);
el.innerHTML=new_t;
}
function grabKey(e){
var e=e? e : window.event;
if(e.keyCode==37)
moveBold(document.getElementById('mb'))
}
if ( typeof document.addEventListener != "undefined" )
document.addEventListener( "keydown", grabKey, false );
else if ( typeof document.attachEvent != "undefined" )
document.attachEvent( "onkeydown", grabKey );
else {
if ( document.onkeydown != null ) {
var oldOnkeydown = document.onkeydown;
document.onkeydown = function ( e ) {
oldOnkeydown( e );
grabKey(e);
};
}
else
document.onkeydown = grabKey;
}
})();
</script>
Bookmarks