Created
September 26, 2013 18:09
-
-
Save r3b/6718179 to your computer and use it in GitHub Desktop.
replace text in place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var iframe = document.getElementById('bannerContent_ifr') | |
function replaceQuotes(text){ | |
return text.replace(/(.)/g,function($1){ | |
var c=$1.charCodeAt(0), n=$1; | |
switch(c){ | |
case 8220: case 8221: | |
n='"'; | |
break; | |
case 8216: case 8217: | |
n="'"; | |
break; | |
} | |
return n; | |
}); | |
} | |
function onDOMModified(event){ | |
var ignoreKeyCodes="13 16 17 18 20 27 33 34 35 36 37 38 39 40" | |
if (ignoreKeyCodes.indexOf(event.keyCode.toString())!==-1) { | |
return; | |
} | |
if(event.target.watchAndReplace===true){ | |
return; | |
} | |
event.target.watchAndReplace=true; | |
iframe.contentWindow.setTimeout(function(){ | |
try{ | |
var selection=iframe.contentWindow.document.getSelection(); | |
var range=selection.getRangeAt(0).cloneRange(); | |
var nodeWithCursor= | |
range.endContainer; | |
window.nodeWithCursorRange=range; | |
var loffset=range.endOffset-(nodeWithCursor.nodeValue.length-range.endOffset); | |
var content=replaceQuotes(nodeWithCursor.nodeValue); | |
nodeWithCursor.nodeValue=content; | |
range.selectNode(nodeWithCursor); | |
range.setStartAfter(nodeWithCursor); | |
selection.removeAllRanges(); | |
selection.addRange(range); | |
}catch(e){ | |
if(console && console.warn)console.warn(e.message); | |
}finally{ | |
console.log("delete our watcher"); | |
delete event.target.watchAndReplace; | |
} | |
},80); | |
} | |
iframe.contentWindow.document.body.addEventListener("focus", function( event ) { | |
event.stopImmediatePropagation(); | |
event.stopPropagation(); | |
event.cancelBubble=true; | |
event.target.style.outline = "1px solid pink"; | |
var doc=iframe.contentWindow.document; | |
doc.addEventListener("keyup", onDOMModified, false); | |
}, false); | |
iframe.contentWindow.document.body.addEventListener("blur", function( event ) { | |
event.stopImmediatePropagation(); | |
event.stopPropagation(); | |
event.cancelBubble=true; | |
event.target.style.outline = ""; | |
var doc=iframe.contentWindow.document; | |
doc.removeEventListener("keyup", onDOMModified, false); | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment