PDA

View Full Version : سوال: make custom text editor with extends "insert Tag" jquery plugin



alismith
شنبه 08 مهر 1391, 20:41 عصر
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery","1.5");
</script>
<script src="jquerypp.custom.js"></script>
<script>
jQuery.fn.extend({
insertTag: function(Tag){

var pattern = new RegExp("(<"+Tag+">)(.*?)(<\/"+Tag+">)","gi");

var sel,html,selection,self = $(this);
html = self.html();
selection = self.selection();
sel = html.substring(selection.start, selection.end);
startPos = selection.start;
endPos = selection.end;
alert(sel); // show selected text for debug ing!
if(pattern.test(sel)){

txt = sel.replace(pattern,"$2");

$(this).html(html.substring(0, startPos) + (txt) + html.substring(endPos,html.length));
}else{
$(this).html(html.substring(0, startPos) + ("<"+Tag+">" + sel + "</"+Tag+">") + html.substring(endPos,html.length));
}

}
});



$(function () {
var design = $('#tbox'),
source = $("#txt");

$('.tag').click(function () {
design.insertTag($(this).val().toLowerCase());
source.html(design.html());
});

design.keyup(function(){
source.html($(this).html());
});

});
</script>
</head>
<body>
<br/>
<input type="button" class="tag" value="B" />
<input type="button" class="tag" value="P" />
<br/>
<div id="tbox" style="width: 300px; height: 300px; border: 1px solid #000;" contenteditable></div>
<br/>
<textarea id="txt" style="width: 300px; height: 150px;"></textarea>
</body>
</html>

there is bug in selected text range, please help me...! :(