Before the button ("play") is clicked, the program handles keydown but after clicking the button which draws a table, thereafter keydown messages are not handled.
I want this to work in IE or Firefox.
<html>
<head>
<script type="text/javascript">
var matrix,xbody,ybody,dir,key;
function draw()
{
for(var i=0;i<xbody.length;i++)
{
matrix[xbody[i]*50+ybody[i]].bgColor="black";
}
alert("draw");
}
function init()
{
document.write("<table id='mine' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >");
for(var i=0;i<50;i++)
{
document.write("<tr>");
for( var j=0;j<50;j++)
document.write("<td></td>");
document.write("</tr>");
}
document.write("</table></div>");
matrix=mine.getElementsByTagName("td");
xbody=new Array();
ybody=new Array();
xbody[0]=ybody[0]=0;
draw();
alert("pop");
}
function keypress(e)
{
alert("aiyoooo");
if((e.keyCode==38)|| ((e.which)&&(e.which==38)))
key=0;
else if((e.keyCode==40)|| ((e.which)&&(e.which==40)))
key=1;
else if((e.keyCode==37)|| ((e.which)&&(e.which==37)))
key=2;
else if((e.keyCode==39)|| ((e.which)&&(e.which==39)))
key=3;
}
</script>
</head>
<body onkeydown=keypress(event)>
<br/>
<input type="button" onClick="init()" value="play">
</body>
</html>
You may want to read this article: http://java-programming.suite101.com/article.cfm/javascript_documentwrite_tutorial
The document.write command must be
carried out during the loading of the
page. So, if it is attached to any
event that executes after the page has
loaded, then the whole page will be
replaced with the contents of the
document.write command.
Rather than using document.write, you might want to instead use getElementById and then put your HTML in the innerHTML property of the element that you want the text to be in.
That may require adding a new div to hold the new text.
Since the answer would be rather long just => look here
in short document.write is just not the right way to go.
use smth different like document.createElement or go for a nice'n'easy javascript framework like jquery.
there you could just
var html = "";
html += "<table id='mine' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >";
html += ...
$(html).appendTo("body");
hope this helps
Related
I am trying to add text to two DIVS with ids= DIV1 and DIV2 in a html page(home.html) from a js page main.js using document.write() command. On clicking the button in html page, the respective text must appear in the hmtl page.
The code is as given below. I keep getting an error: document.write can be a form of eval. Is there a possible way of using document.write() and print the text in the div sections.
HTML code:
<head>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
</body>
JAVASCRIPT code:
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.write('<div id="div1">'+"Name:"+ arr.name +'</div>');
document.write('<div id="div2">'+"School:"+ arr.school +'</div>');
}
Name:abc
School:pqrst
...using document.write() command
Don't. Only use document.write during the initial parsing of the page, or to write to a new window you've just opened (or better yet, don't use it at all).
Instead, use the DOM. Example:
function xyz(){
var arr = {name: "abc", school: "pqrst"};
addDiv("name", "Name:" + arr.name);
addDiv("age", "School:" + arr.school);
}
function addDiv(id, content) {
var d = document.createElement("div");
d.id = id;
d.textContent = content;
document.body.appendChild(d);
}
<input type="button" value="click!" onclick="xyz()">
If you have an HTML string you want to insert, you can do that with insertAdjacentHTML, but beware of combining text from an object with HTML, because any < or & in the text must be escaped correctly (more than that if you're going to put the content into an attribute, as with your id values). It happens that your two example values don't have those characters, but you can't assume that in the general case.
You can use insertAdjacentHTML() in place of document.write(). Refer this for more details
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="name">'+"Name:"+ arr.name +'</div>');
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="age">'+"School:"+ arr.school +'</div>');
}
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
I have been struggling with this so hopefully someone can help!
So I am looking to change the inner html of a paragraph to another html element containing a div and script when my frame receives a message from the page code. I have this working only for when the inner html is set to replace with a normal string
like this
document.getElementById('demo').innerHTML = "testing" ;
the correct replacement shows up here
<p id="demo">testing</p>
but when I try and pass in the other html to replace that section like this:
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>';
it does not work. I don't think it is a quotation issue because I wrapped the outsides of it with single quotes. not sure what else to try. Below is the full html and I would appreciate any help!
<!doctype html>
<html>
<head>
<script type="text/javascript">
function init () {
// when a message is received from the page code
window.onmessage = (event) => {
if (event.data) {
console.log("HTML Code Element received a message!");
insertMessage(event.data);
}
}
}
// display received message
function insertMessage(msg) {
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>'
;
}
</script>
</head>
<body onload="init();" style="background-color:lightgray;">
<h1>HTML Component Test</h1>
<p id="demo">
should put html here
</p>
</body>
</html>
The major issue is the </script> closing tag in your code. It closes YOUR block, not the block you are inserting.
You have to do so:
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></scr"+"ipt>";
Second, script you insert with innerHTML wont run. Use document.createElement('script') instead
UPDATE
Here is the jsFiddle: https://jsfiddle.net/ArtyomShegeda/62fdybc0/21/
You may consider swapping the Quotes used:
function insertMessage(msg) {
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></script>";
document.getElementById('demo').innerHTML = myHtml;
}
This may add it, yet may not render it. You might consider creating the elements and appending them.
function insertMessage(msg) {
var tlkio = document.createElement("div");
tlkio.style.width = "100%";
tlkio.style.width = "400px";
tlkio.setAttribute('data-channel', 'regerhtrh');
tlkio.setAttribute('data-theme', 'theme--night');
var tlkScript = document.createElement("script");
tlkScript.src = 'https://tlk.io/embed.js';
tlkScript.type = 'text/javascript';
tlkScript.async = true;
document.getElementById('demo').append(tlkio, tlkScript);
}
Based on some research here: load scripts asynchronously, it may be best to append the script to the <head>.
Hope that helps.
Update 1
Per your fiddle, once updated, it is working as you suggested: https://jsfiddle.net/Twisty/62fdybc0/7/
The following is added to #myDIV element:
<div style="width: 100%; height: 400px;" data-channel="regerhtrh" data-theme="theme--night"></div><script src="https://tlk.io/embed.js" type="text/javascript" async="async"></script>
Does anyone know why this simple program doesn't work?
It's a program that creates a group of radio buttons with Javascript.
<html>
<head>
<script>
function onWriteRadio(Valuse,numButtons,RadioName){
for(i=0;i<numButtons;i++){
document.write("<input type='radio' name=" + RadioName + "value=" +Valuse[i]+"/>");
document.write("<br/>");
}
}
</script>
</head>
<body onload="onWriteRadio([red,green,blue],3,'color')>
</body>
</html>
use this:
onWriteRadio(['red','green','blue'],3,'color')
string the array values. Currently, you say [red,green,blue], that means the variable red, variable green, variable blue, BUT you don't define them anywhere, so your program is saying "hmm, i do not know what red is.".. so string em.
put array values in quotes
onWriteRadio(['red','green','blue'],3,'color')
you left some quotation marks.
function onWriteRadio(values, radioName){
for (var i = 0; i < values.length; i++) {
document.write("<input type='radio' name='" + radioName + "' value='" +values[i]+"' >"+values[i]+" </ input>");
document.write("<br/>");
}
}
<html>
<body onload="onWriteRadio(['red', 'green', 'blue'], 'color')">
</body>
</html>
document.write() writes HTML expressions or JavaScript code to a document, which replaes your earlier html content.
document.write() executed after the page has finished loading will overwrite the page, or write a new page.
document.write() is a bad practice
place array values in quotes
add closing double quote for onload
make one string containing all inputs code and then write it
Your code should look smthng like this:
<html>
<head>
<script>
function onWriteRadio(Valuse,numButtons,RadioName){
var s = '';
for(i=0;i<numButtons;i++){
s += "<input type='radio' name=" + RadioName + "value=" +Valuse[i]+"/>"
}
document.write(s);
}
</script>
</head>
<body onload="onWriteRadio(['red','green','blue'],3,'color')">
</body>
</html>
i have xml file which contains lots of data. now i want to pick a price with some condition. i set a parameteres in javascript function but it is not giving desire result. i think it can be done through childnode but i didnot aware about that
XML file
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="PER" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="SYD" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
HTML page
<head>
<script type="text/javascript">
function myXml(origin, destination ) {
var x = xmlDoc.getElementsByTagName("flights");
for(i=0; i<x.length; i++) {
if (x[i].getAttribute('FrTLAs') == origin
&& x[i].getAttribute('destination') == destination) {
alert(x[i].getAttribute('price'))
}
}
}
</script>
</head>
<body>
click me
</body>
did u miss this??
xmlDoc=loadXMLDoc("flights.xml");
chk this page
http://www.w3schools.com/dom/prop_element_attributes.asp
the example2 is very clear how to use this
x=xmlDoc.getElementsByTagName("book")[0].attributes;
//here its would be getElementsByTagName("flights") in the loop
//then .attributes on it
// and then this
frtlas=x.getNamedItem("FrTLAs");
desti=x.getNamedItem("destination");
//and your code here
hope this helps
<html>
<head>
<style type="text/css">
body {
background-color: #000000;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
text-align: center;
color: #FFFFFF;
}
</style>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
function sleep(ms)
{
var dt = new Date();
dt.setTime(dt.getTime() + ms);
while (new Date().getTime() < dt.getTime());
}
function update() {
while (0 < 1) {<?php $contents = file_get_contents("my url here");
?>
var count = <?php echo $contents ?>;
document.getElementById('div').innerHTML = count;
sleep(1500);
}
}
</script>
</head>
<body onload=update()>
<iframe id="iframe" src="my url" style="visibility: hidden;"/>
<table width=100% height=100%>
<tr height=80%>
<td width=100%>
<center>
<div id="div"></div>
</center>
</td>
</tr>
</table>
</body>
</html>
When viewing the source code in-browser, the var is set correctly, but it won't set the content of the div. I am positive that the url the PHP script is pointing to is accurate and contains only a script to grep a number from an external page.
Thanks in advance!
To answer the question, why isn't it running... your onload needs quotes:
<body onload="update()">
but the others have posted better ways to go about it using jquery.
Assuming that the value of file_get_contents("my url here") yields 42 (for example), you are aware that you're creating an infinite loop which will set the content of #div to 42 over and over again every 1.5 seconds? I.e., var count will always, constantly be 42 and won't change, since PHP is evaluated only once on the server.
Furthermore I would suspect that your sleep function could pose a bit of a problem, since it creates another tight loop. I wouldn't be surprised if this script simply blocked the browser without ever updating anything since it's caught in an infinite loop. The way to delay execution in Javascript is to use window.setTimeout or window.setInterval.
I guess what you're looking for is an AJAX solution of some kind, if you would tell us what it is you want to do. Since you're including jQuery (without actually using it), you should have a look at jQuery.get(), coupled with a setInterval to update the div periodically.
Something like:
window.setInterval(function () {
$.get("my url here", function (data) {
$('#div').html(data);
});
}, 1500);
var count = <?php echo $contents ?>;
document.getElementById('div').innerHTML = count;
You are asking the webserver for variable $contents through php, which will always be a static number unless you reload the page. Try using jQuery, as the poster above mentioned.