Reputation: 24305
I'd like to make my own text editor. I'm trying to follow the example of several other well established editors and use a hidden <textarea>
and visible <iframe>
combo.
I'm having trouble with the very first step of keying up the <iframe>
. I can get execCommand to work on a contenteditable <div>
to, e.g., make text BOLD but having trouble doing the same on the <iframe>
.
Here's my HTML:
<html>
<button type="button" class="btn btn-bold">bold</button>
<textarea id="input" name="input" style="display: none;">Start typing..</textarea>
<iframe frameborder="0" src="javascript:true;" style=""> </iframe>
</html>
Here's my JavaScript:
$(function() {
var currentBtn;
$("#input").focus(function() {
currentBtn = this;
});
$(".btn").on( 'click', '.btn-bold', function(){
var $this=$(this);
if($this.hasClass("btn-bold")){ document.execCommand('bold', false, null);}
$(currentBtn).contents().focus();
});
});
I know I need to perform the execCommand on the iframe document and not the parent document but just not sure how to do this. Currently, this code doesn't allow me to keyup the iframe so can't test the effect of the bold button.
Any thoughts would be greatly appreciated!
Upvotes: 1
Views: 3631
Reputation: 71
This might help.But it in in javascript and I am running it in google chrome.Here is the code:
<div>
<input type="button" onClick="bo()" value="B">
<input type="button" onClick="under()" value="U">
<input type='button' onClick="f_size()" value="f_size">
<br>
<iframe name="richTextField" id="richTextField" style="border:#000000 1px solid; width:700px; height:300px;"></iframe><br>
<input type="button" onClick="asd()" value="get_innerhtml"><br>
<textarea name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
</div>
<script>
richTextField.document.designMode = 'On';
function bo(){
richTextField.document.execCommand('bold',false,null);
}
function under(){
richTextField.document.execCommand('underline',false,null);
}
function f_size(){
var size = prompt('Enter a size 1 - 7', '');
richTextField.document.execCommand('FontSize',false,size);
}
function asd(){
var text=document.getElementById('richTextField').contentWindow.document.body.innerHTML;
document.getElementById('myTextArea').value=text;
}
</script>
Upvotes: 0
Reputation: 94299
Use Rangy and wrap <b>
around the selection to bold. You can perform other tasks with this method too.
Demo: http://rangy.googlecode.com/svn-history/r511/trunk/demos/core.html
How to make iframe
editable:
window.frames[0].document.getElementsByTagName("body")[0].contentEditable = true;
Upvotes: 2