Page 1 of 1

Javascript - insert Image/HTML tags

Posted: Mon Mar 19, 2007 9:30 am
by Skittlewidth

Code: Select all

function insertAtCursor(myField, myValue) {
  //IE support
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  //MOZILLA/NETSCAPE support
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
                  + myValue
                  + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}
// calling the function
insertAtCursor(document.formName.fieldName, '<img src=\'http://newsimg.bbc.co.uk/media/images/42682000/jpg/_42682869_composite416x152.jpg\' width=100 height=100/>');
I'm still playing with Javascript and I've come across this code with allows me to click a button and assign text at the cursor position, or over the selected text in a text area or a content editable div etc... That's well and good but if I insert html, like the image tag above it will appear literally. I know that's all the textarea can do, but what about a div? How do I do what FCKEditor and other RTEs do and get the container to render the html? I've tried delving into the FCK code but its going way over my head.

Posted: Mon Mar 19, 2007 11:07 am
by mikeq
maybe browse Google for innerHTML

Posted: Mon Mar 19, 2007 11:51 am
by Kieran Huggins
"insert at cursor" is a tricky concept - I think you're actually playing with the selected text (which is selecting 0 characters) - hopefully that will help?

I've used some pre-made functions for selecting / replacing text before - search and you'll find some on the net.

Posted: Mon Mar 19, 2007 12:31 pm
by Skittlewidth
The insert at cursor bit is sorted in the code above. (I have found some other code somewhere that can put tags either side of the selected text) I'd just like the resultant html to actually render rather than just display the HTML tags within the editable area. InnerHTML is probably the way to go, but delving into FCK a bit further I'm beginning to see that what's going on is a little bit more complicated than that - and why it has to use IFrames.

Thanks for the suggestions though.
I've got no problem with just using these pre-built utilities but my new employers seem to like to build everything from scratch so I really want to understand how these things actually work.

Posted: Wed Apr 18, 2007 12:20 am
by ryan_mate
Thanks for the code, it served me well.

In regards to your actual question about pasting HTML if it were an editable DIV..

rather than using:
sel.text = '<span>Hello</span>';

use this:
sel.pasteHTML('<span>Hello</span>');

This way, the HTML will not display as text, it will be treated as HTML within the DIV.


- Ryan