Jump to content

setTimeout to detect changes in a text field


Rain Lover

Recommended Posts

I wonder why the following sample code doesn't work properly:

<!DOCTYPE html><html>		<head>		<title></title>		<style type="text/css">			textarea, iframe {				display:block;				width:300px;				height:100px;				margin:3px;				padding:3px;				border:1px solid #CCC;			}		</style>	</head>		<body>		<textarea id="field" onfocus="getFocus();" onblur="loseFocus();">This is some text.</textarea>		<iframe name="target"></iframe>		<script>			var textarea = document.getElementById('field');			var iframe = window.target.document; 			function displayResult() {				if (textarea.value) {					iframe.open();					iframe.write(textarea.value);					iframe.close();				}				window.setTimeout(displayResult, 10);			} 			function getFocus() {				if (textarea.value == textarea.defaultValue) {					textarea.value = '';				}			} 			function loseFocus() {				if (textarea.value == '') {					textarea.value = textarea.defaultValue;				}			}			displayResult();		</script>	</body> </html>

Demo: http://jsfiddle.net/RainLover/4ksMR/ The iframe content is supposed to get updated in real time -- as soon as the textarea content changes by keyboard or mouse. This approach is an alternative to the oninput event. But since oninput isn't well-supported across different browsers I decided to create a timer to compare the current text field value with its value in 10 milliseconds before.

Edited by Rain Lover
Link to comment
Share on other sites

First of all, give the iframe an ID attribute and use getElementById() to access it. While some browsers may set "target" to the iframe element, that's non-standard behavior.

Link to comment
Share on other sites

First of all, give the iframe an ID attribute and use getElementById() to access it. While some browsers may set "target" to the iframe element, that's non-standard behavior.
I tried id, but it didn't work:
var iframe = document.getElementById('target');             function displayResult() {                if (textarea.value) {                    iframe.open();                    iframe.write(textarea.value);                    iframe.close();                }                window.setTimeout(displayResult, 10);            }

I also updated my question for clarification.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...