I'm trying to make a WYSIWYG editor, and so far I have it so you can select text and click 'Make Bold' to make the selected text bold. It literally just wraps < b> (no space) tags around the selected text. But my problem is that if I want to un-bold that, my script has some trouble...
So far, here is my script:
<script language="javascript">
function format(tag) //defines function format
{
var editor = document.getElementById('editor');
var txt = '';
var tester = document.getElementById('tester');
if (window.getSelection) //if your browser uses this method of text selection
{
txt = window.getSelection();
}
else if (document.getSelection) //if your browser uses this method of text selection
{
txt = document.getSelection();
}
else if (document.selection) //if your browser uses this method of text selection
{
txt = document.selection.createRange().text;
}
else return; //Return this
matched = editor.innerHTML.match(txt); //Find the selected text in the editor
// if (matched.style.font-weight = "600") {tester.innerHTML = "already bold";} //if the selected text is bold, say 'already bold' DOES NOT WORK
// else {tester.innerHTML = "not bold";} //if it doesn't...
editor.innerHTML = editor.innerHTML.replace(matched,"<"+tag+">"+matched+"</"+tag+">");//Wrap <b> tags around it
}
</script>
<input type="button" value="Make Bold" onmousedown="format('b')">
<input type="button" value="Make Italic" onmousedown="format('i')">
<div id='editor' onclick="javascript:this.designMode='on';" designmode="on" contenteditable="true">Edit Box</div>
<span id="tester">testing span</span>
If you try it out you can type in that box and select text and click Make Bold and it will be bold. Now click Make Bold again but nothing happens. It's just adding another < b> tag around the selected text. I want it to make it un-bold; normal.
How do I do that?
Thanks :)