Summary/Background
I'm trying to make a contenteditable div and when it was pasted by the HTML words, I hope that it could be transferred into plain text and the caret could jump to the end of the pasted HTML words automatically.
My try
I have tried to make it, and below is my code I have typed.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function stripHTML(input){
var output = '';
if(typeof(input) == "string"){
output = input.replace(/(<([^>]+)>)/ig, "");
}
return output;
}
$(function(){
$("#text").focus(function(event){
setItv = setInterval('clearHTML()', 1);
});
$("#text").blur(function(event){
clearInterval(setItv);
});
});
function clearHTML(){
var patt = /(<([^>]+)>)/ig;
var input = $("#text").html();
if(input.search(patt) >= 0){
var output = '';
if(typeof(input) == "string"){
output = stripHTML(input);
}
$("#text").html(output);
}
}
</script>
<div contenteditable="true" style="border: 1px #000 solid; width: 300px;
height: 100px;" id="text">Hello, world!</div>
</body>
</html>
Issue
The biggest issue is the cursor placement. After pasting the HTML in the middle of the original text (e.g., paste between “Hello” and “world”), the caret would jump to the end of the whole text not the end of the pasted HTML. Normally, when we paste a snippet of words in the middle of the original text, the caret would jump to the end of the pasted words, not the end of the whole text. But in this case I don't know why it jumps to the end of the whole text automatically.
And the secondary issue is that the setInterval function. Maybe it doesn't cause any problem, but the way of scripting is extremely unprofessional and it may impact the efficiency of the program.
Question
- How to prevent the caret from jumping to the end of the whole text in contenteditable div after pasting the HTML words in the middle of the original text?
- How to optimize the scripting without using the setInterval function?
` tag. – Banana Code May 19 '15 at 01:42
` tag in the contenteditable div box. Then you might see the error. I don't know why the contenteditable div in my IE11 acted wrongly and didn't strip the HTML tags. Is my computer's IE11 broken? – Banana Code May 19 '15 at 10:55