I wrote the following code: <script type="text/javascript"> setTimeout("runscript()",2000); function runscript() { document.write ("<div id='iframe'><input type='button' value='Close' onclick='Close();'></div>") } function Close() { var iframe = document.getElementById('iframe'); iframe.style.display = 'none'; } </script> This should show a <div> with a button after two seconds. Then when you click on the button, it should hide the <div> But the function "Close()" does not work! I get an error "Object required" Does anyone know what is wrong in the code?
Don't use write() to add code to a page that has already been loaded. The browser starts a new page with just the button markup, but it lacks the HTML structure that makes it a webpage. Either create new DOM nodes or change the contents of existing ones, by using innerHTML(). Try this! <html> <head> <title>Demo</title> <script type="text/javascript"> window.onload = function() { setTimeout("runScript()", 2000); } function runScript() { document.getElementById('iframe').innerHTML = "<input type='button' value='Close' onclick='Close();'>"; } function Close() { var iframe = document.getElementById('iframe'); iframe.style.display = 'none'; } </script> </head> <body> <div id='iframe'></div> </body> </html> Code (markup):
Thanks Cash Nebula I need it to be on a javascript file So I upgraded it even more: <script type="text/javascript"> setTimeout("runscript()",2000); function runscript() { document.getElementById('iframe').innerHTML=("<table width='100%'><tr><td width='50%' align='left'><a target='_blank' href='http://www.easytraffic.biz'><img border='0' src='http://www.easytraffic.biz/Images/DPIcon.gif' width='283' height='20'></a></td><td width='30%' align='right'><input type='button' value='Close' onclick='Close();'></td></tr></table><iframe height='100%' width='100%' src='http://www.google.com'></iframe>"); } function Close() { document.getElementById('iframe').style.display = 'none'; } document.write ("<div id='iframe'></div>") </script>
you need to change the document.write line.. its better to use. <script type="text/javascript"> setTimeout("runscript()",2000); function runscript() { document.getElementById('iframe').innerHTML=("<table width='100%'><tr><td width='50%' align='left'><a target='_blank' href='http://www.easytraffic.biz'><img border='0' src='http://www.easytraffic.biz/Images/DPIcon.gif' width='283' height='20'></a></td><td width='30%' align='right'><input type='button' value='Close' onclick='Close();'></td></tr></table><iframe height='100%' width='100%' src='http://www.google.com'></iframe>"); } function Close() { document.getElementById('iframe').style.display = 'none'; } Â Â document.body.innerHTML = "<div id='iframe'></div>"; Â </script>Â HTML: Â Â