Dark Bit Factory & Gravity

ARCHIVE => Archive => Java,JS & Flash => Topic started by: mike_g on March 14, 2007

Title: Updating text on a page
Post by: mike_g on March 14, 2007
Hey benny, heres (http://mike_g.sitesled.com/Binary Game.zip) the code for the javascript game I made, with css and all. Be warned its pretty crude. Bascially you get 3 minutes to answer as many questions as possible. You score 10 points for each correct one, and lose 5 for each one thats wrong. Oh yeah version 1 works, version 2 dosent.

Heres my problem: At the moment the only way I know how to update text on the screen is by either having it inside a form field, or by redrawing the entire page. You will notice that the target score is in a form field, but I would like it drawn in text.

I figured that it should be possible to update it by creating an object for it and then writing a member function for the object to update the text since the timer and input fields are both capable of doing this. In version 2 I got the target set as a variable in an object but when it changes I dont know how to update it on the screen ???  cheers :)




Title: Re: Updating text on a page
Post by: benny! on March 14, 2007
@mike_g:

1st - I am really impressed. The game is well designed and looks very cool.

I think the easiest way to simply update a certain region in a html file is to
use the innerHTML property of e.g. <div> tags. Here is a little
example I wrote that might help you :

Code: [Select]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Updating text on a page</title>
<script>
function updateText() {
document.getElementById( "updatedArea" ).innerHTML = "Text updated!";
}
</script>
</head>
<body>
<div id="updatedArea">This text will be updated</div>
<a href="javascript:updateText();">Update</a>
</body>
</html>


As you can see, I wrapped a <div> tag around the region which I want to update.
In the javascript funtion I simply grab the div with the document.getElementById()
function and set a new property to innerHTML. Thats basically all.

Hope this helps you. And again - your game looks cool!
Title: Re: Updating text on a page
Post by: mike_g on March 14, 2007
Thanks man, your codes helpful :)

I'll make mine so that its using divs then. If i find the time i might make a version using images instead of those tiny checkboxes too. 
Title: Re: Updating text on a page
Post by: benny! on March 14, 2007
I am happy that I could help.

You should definately finish it. I really do like it. And with all that javascript and ajax
hype going on atm - I think such a nice javascript game would get good recognition.
Title: Re: Updating text on a page
Post by: mike_g on March 14, 2007
I'm glad you like it :) At the end of the day though a game cant get much simpler than this. If I find the time i'll try and add some variety. Shockwave had a couple of good suggestions earlier.
Title: Re: Updating text on a page
Post by: benny! on March 14, 2007
Yup. Using different systems next to binary like hex would be a nice addition.
Although I think the binary is the geekiest of them ;-)

Anyway, please do keep us informed whenever you make a new version !!!
Title: Re: Updating text on a page
Post by: mike_g on March 14, 2007
Will do  ;)
Title: Re: Updating text on a page
Post by: mike_g on March 23, 2007
Hey benny! I have been playing around with javascript a bit more today and made an update of that game I made. Things are a bit more polished, the games now got levels that get harder, and every second level is in hex.


You can play it here (http://mike_g.sitesled.com/BinaryGame/Binary%20Game.htm). Cheers.
Title: Re: Updating text on a page
Post by: benny! on March 23, 2007
@mike_g:

Just awesome ! Very cool ... although I sucked at my first try :

Quote
Game Over. You scored: 35 points.

One thing I would change though would be the Game Over
screen. Maybe a little <div> just beneath the actual game and
update that, when a game is over.

Nevertheless, great javascript-game  :goodpost:

If you are familiar with php and your host support it - a little high-
score system would be rocking ;)

Keep it up!
Title: Re: Updating text on a page
Post by: mike_g on March 23, 2007
Yeah the game over thing sux. Its one of the bits I havent got around to yet. Might try and make it so that the earlier levels give you easier numbers to work out rather then just random generated. Maybe I should make the time limit a little longer too. I dont know anything about PHP yet, but I'll be doing it soon in college. So when I get around to it I might add a highscore table. Cheers :)
Title: Re: Updating text on a page
Post by: Shockwave on March 24, 2007
I am thick :) I only scored 35.
Title: Re: Updating text on a page
Post by: p01 on March 24, 2007
In the javascript funtion I simply grab the div with the document.getElementById()
function and set a new property to innerHTML.  basically all.
It updates the content of the node, granted.
But this is not the way to go. It can be unsafe ( JavaScript can be injected and IS executed ), and last but not least it nukes the event listeners of the updated node and its children ( if you append to the innerHTML instead of replacing it ).

What you should do instead is:



If need be I can provide the code of my sanitizer.

Hope that helps,
Title: Re: Updating text on a page
Post by: mike_g on March 24, 2007
Hey thanks for the advice. I hadent really thought about code injection stuff yet. Most of the terms you are talking about I don't quite get yet, but are you saying that the stuff to update should get validated before it gets chucked into the element? If possible a code example could be helpful. Cheers.
Title: Re: Updating text on a page
Post by: p01 on March 24, 2007
You should not trust what you receive, especially content from an external source. If you want to update the display of something, use textNodes, or sanitize the input.

The idea is to remove undesired and potentially harmful elements and attributes ( such as inline style and events that can be used for script injection ) before you append them in the document. To do so, DOM manipulation outruns string manipulation. Any day.

What you receive from an XHR, or any other function, may not be valid XML ( mostly due to badly nested nodes, bad entities, ... ) and thus DOM methods are not available.

When you do elementFoo.innerHTML = textVersionOfMarkup the browser cleans the crap and generate a usable DOM tree on which you can call any regular DOM methods such as adding/updating/removing nodes/attributes.


FWIW, I prefer to use a white-list of nodes and attributes. This way I'm sure of what I'm up to inject in my document.


:P the code is not on my USB stick. I'll post it next time I go to the office ( which might be tomorrow :( as I have to finish something before our team meeting on monday morning )
Title: Re: Updating text on a page
Post by: Shockwave on March 24, 2007
Fuck, you can have some good karma for having to work on Sunday as well as giving some good advice. Thanks.
Title: Re: Updating text on a page
Post by: mike_g on March 24, 2007
Okay I just updated my game. The new bits are:

-Buttons drawn as images instead of those fiddly checkboxes
-Game dosent start until you click begin.
-On game over the game gets reset.
-Your highscores get saved to a cookie.
-Time limit set higher.

I'm finished with it now, except perhaps if it would be good to change some of the stuff that uses innnerHTML. Heres the link to it again (http://mike_g.sitesled.com/BinaryGame/Binary%20Game.htm). Cheers.
Title: Re: Updating text on a page
Post by: p01 on March 25, 2007
I hadn't try the game before. It's fun, I just scored 354  8)

The code is a bit oldschool  :P
HTH
Title: Re: Updating text on a page
Post by: p01 on March 25, 2007
It'd rock if you logged the clicks to have a replay of the high score  :D
Title: Re: Updating text on a page
Post by: mike_g on March 25, 2007
Thanks man. I'll try use some of your suggestions to make the code better. It would be nice not to have to use document.write all the time.  And yeah logging the clicks is a cool idea :)
Title: Re: Updating text on a page
Post by: benny! on March 25, 2007
@mike_g:

Damn, your game gets better and better. I really like the design as well !!!
Adding counting clicks and some highscore just would make it perfect!


@p01:

Never thought about checking incoming values before. Thanks for pointing
that out and your advanced explanation. Definately, Karma up.

I'll will keep this in mind next time I code in javascript.


@topic:

Code: [Select]
if( tmp!=null && tmp.firstChild!=null && tmp.firstChild.nodeType==3 )
Here is a list of available nodeTyp values :

http://www.javascriptkit.com/domref/nodetype.shtml (http://www.javascriptkit.com/domref/nodetype.shtml)
Title: Re: Updating text on a page
Post by: mike_g on March 25, 2007
@p01: Thanks for the Css Sprites link. I managed to sort out a small tileset for a new little game doing that stuff. I have kind of left my binary game at the moment, but I did try and replace my UpdateText function with yours. I couldent seem to get it to work though. I dont know why, maybe it has something to do with what I'm putting into the function elsewhere in the prog, or am I missing something here? Anyway thanks for all the help.

@benny: Thanks for the link. Helped me get a bit better idea of what all the nodes are about. I'll have to learn more about it.
Title: Re: Updating text on a page
Post by: p01 on March 28, 2007
Here it comes:
Code: [Select]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>

<style type='text/stylesheet' >

#foo
{
border:1px solid #c30;
background:#ffc;
padding:1em;
}

</style>
<script type='text/javascript'>

// /!\ tabSize = 4


/**
 * the whiteList of tags and their attributes
 */
var _whiteList =
{
'A':['href'],
'STRONG':[],
'P':[],
'EM':[],
'H1':['style'],
'BR':[]
}


/**
 * Prototype extension to simplify adding and sanitizing markup to an element.
 * arguments = some strings containing the HTML markup to sanitize and append
 */
HTMLElement.prototype.appendMarkup = function()
{
var dummy = document.createElement('div');
dummy.innerHTML = arguments.join('') // /!\ the following replacements are optionnal
.replace( /&gt;/g, '>' ) // replace commonly over-encoded characters.
.replace( /&lt;/g, '<' )
.replace( /&amp;/g, '&' )
.replace( /&nbsp;/g, ' ' )
.replace( /&quot;/g, '"' )
.replace( /((\\[nr])+|[\r\n]+)/g, '<br/>' ) // replace multiple [\n\n] and badly encoded [\n\r] by <br/>
.replace( /<!\[CDATA\[(.*)\]\]>/gi, '$1' ) // remove <[CDATA[ .* ]]> delimiters

dummy.sanitize( _whiteList )

// append DOM tree of dummy in this
while( dummy.firstChild )
this.appendChild( dummy.firstChild.cloneNode( true ) ),dummy.removeChild( dummy.firstChild );
}



/**
 * Prototype extension to sanitize the attributes and HTMLElements
 * whiteList = { 'NODENAME_0':['attribute_0','attribute_1'] }
 */
HTMLElement.prototype.sanitize = function( whiteList )
{
var whiteList = whiteList||{},
nodeName = this.nodeName;

// build local whiteList
if( whiteList[nodeName] && typeof(whiteList[nodeName])!='string' )
whiteList[nodeName] = ' '+(whiteList[nodeName]||[]).join(' ').toUpperCase()+' ';
var localWhiteList = whiteList[nodeName]||'@';

// sanitize the attributes
for( var i=0,attribute; attribute=this.attributes[i]; i++ )
if( localWhiteList.indexOf( attribute.name )+1 )
this.removeAttribute( attribute.name );

// recurse
var i=0, currentNode;
while( currentNode=this.childNodes[i] )
{
if( currentNode.nodeType!=1 )
{
// not an ELEMENT_NODE -> keep it
i++;
continue;
}
else if( typeof(whiteList[currentNode.nodeName])!='undefined' )
{
// in the nodeNamesWhiteList -> recurse
HTMLElement.prototype.sanitize.apply( currentNode, whiteList );
i++;
continue;
}

// not in the nodeNamesWhiteList -> push the content here and throw away the currentNode
while( currentNode.firstChild )
{
this.insertBefore( currentNode.firstChild.cloneNode( true ), currentNode );
currentNode.removeChild( currentNode.firstChild );
}
this.removeChild( currentNode );
}
}



onload = function()
{
var before = new Date()
document.getElementById('foo').appendMarkup( '<h1 style="color:orange;">damer<\/h1><script>alert("aaaaaaar!!!1")<\/script><img src=toto.gif \/><p>qpwoutqopwu <em>tqw<\/em> pouqw tpqwotu q<\/p><sc<'+'![CDATA[ri]]>pt>document.body.bgColor="tan";<\/sc<'+'![CDATA[ri]]>pt>)'+'po<strong>up<\/strong>twq' );
alert( (new Date()-before) +' ms' )
}



</script>
</head>
<body>

<div id='foo'></div>

</body>
</html>

Notice that I wrote the sanitizer for widgets and webApps on mobile and various devices, so I've only used it in Opera.

I worked a bit on a version where you can execute a method before and after processing a node of the whiteList. This will allow to do some magic, add nodes, attributes, ...

It shouldn't be too hard to get it working in Firefox and Safari. For crap^WIE you'll need to replace the extension of the HTMLElement prototype by some ugly-ugly regular functions. Duuuh!

But it's doable.


Sorry for the delay ( see the *sigh* coders can be so anal. (http://dbfinteractive.com/index.php?topic=1632) thread for more details on that ), and thanks for the Karma!
Title: Re: Updating text on a page
Post by: p01 on March 29, 2007
*bump for the few people interrested*
Title: Re: Updating text on a page
Post by: mike_g on March 29, 2007
Hey I hadent noticed this. Thanks for posting the code, I'll be checking it out. Cheers :)
Title: Re: Updating text on a page
Post by: p01 on March 31, 2007
You're welcome.

FWIW, I'm not happy with the use of a global variable for the white list. It should probably be part of the prototype of the HTMLElement object.