...

View Full Version : Percentage timing randomizer



Deacon Frost
08-19-2008, 02:39 AM
This part is solved, post #17 has the next issue! Please read that :D!




Alright, I have been searching as hard as I can, and trying to figure out how to compile this all. But I really can't figure it out.

I'll include below what I have, but here's what I need:

I need a script that generates a random number based on a percentage chance. Lets say a person has a 10% chance to get a 100, and in order for the script to return true the number must be 100 or greater. So I need it to generate the number based on that person's 10% chance. Not only that, but if it returns false, I need to add 2% to the person's chance, and redo it until it returns true, or it is stopped. It needs to wait 2 seconds in-between each new roll.

So I have all the scripts I need, I'm positive, they all come from w3schools, or various places. They each do the function separately, but I'm getting a headache trying to figure out how to combine them.



function generate(){
var randomnumber=Math.floor(Math.random()*101)
}



if (chance => '100')
{
document.write("You successfully got the log.");
}
else
{
+2%
}


setTimeout("document.getElementById('txt').value='2 seconds!'",2000);


<script type="text/javascript">
for (i = 0; i <= 5; i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>



<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>



function() {
if(number == 100) {
return true
} else {
return false +2 chance
}

});

The bottom one is basically what is gonna output, the others are just the randomizing/checking, etc.

I'm going to be putting this on a form of sorts, and it'll just output text, which the return true will do. But it'll basically be called upon through php, if that helps.


:(. My head hurts.


Thanks if anyone can help, ask questions, and I'll answer to the best I can.

Trinithis
08-19-2008, 06:54 AM
What is the valid range of random numbers? Got an an equation on how to generate them as well?

Trinithis
08-19-2008, 07:10 AM
Something like this?



function genRand(chance) {
var rand = chance >= Math.random() * 100
? Math.random() * @@@ + 100 // change @@@ to any non-negative number that suits you
: Math.random() * 101
;
if(rand >= 100)
alert("Your number is " + rand);
else
setTimeout(function() {
genRand(chance + 2);
}, 2000);
}

Deacon Frost
08-19-2008, 07:11 AM
What is the valid range of random numbers? Got an an equation on how to generate them as well?

0 - 100

And not really, I think that's what's mainly confusing me. Generally I take other scripts to cut em up, combine em, splice em, etc... :( ... so actually doing from scratch isn't my best ability.


I keep wanting to go about it in php:


$chance * randomnumber
if(this <= 100) { fail } if(this >= 100) { WIN }


Or summat...

But basically the problem is I need it to randomly generate a number based on the percentage chance. So say again that i have a 10% chance at getting 100, 90% of the time I will get =<99.

Then for every time it returns false, it adds 2% chance to the 10%.

So:

1st Try: 10%
2nd Try: 12%
3rd Try: 14%


And so on. But in-between each new try needs to be a 2 second display :P.

Arbitrator
08-19-2008, 07:42 AM
I need a script that generates a random number based on a percentage chance. Lets say a person has a 10% chance to get a 100, and in order for the script to return true the number must be 100 or greater. So I need it to generate the number based on that person's 10% chance. Not only that, but if it returns false, I need to add 2% to the person's chance, and redo it until it returns true, or it is stopped. It needs to wait 2 seconds in-between each new roll.Iíve created a demo that does what I believe that you requested (though the output isnít identical).

It looks like there was an error in the code. The lines reading var delay = window.setInterval(draw_number, 2000); should read:


if (r !== 100) {
var delay = window.setInterval(draw_number, 2000);
}

Iíve rectified this issue in the posted and live code.
Live Example:

HTML: http://www.jsgp.us/demos/cf146939-ten-percent-chance-at-one-100.html.php
XHTML: http://www.jsgp.us/demos/cf146939-ten-percent-chance-at-one-100.xhtml.php


HTML with PHP:

<?php
ob_start();
header("Content-Type: text/html; charset=UTF-8");
header("Content-Script-Type: application/ecmascript");
header("Content-Style-Type: text/css");
?>
<!doctype html public "-//W3C//DTD HTML 4.01//EN">

<html lang="en-Latn">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Script-Type" content="application/ecmascript">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>Demo for CodingForums.com Thread 146939 (HTML)</title>
<meta name="Author" content="Patrick Garies">
<meta name="Created" content="2008-08-18">
<meta name="Revised" content="2008-08-19">
<style type="text/css" media="all">
* { margin: 0; padding: 0; }
html, h1, h2 { font: 16px/1.2 sans-serif; }
html { background: #ded url("bg_c.png"); color: black; }
h1 { opacity: 0.8; padding: 2em; background: white; font-weight: bolder; }
a { color: black; }
h2, ul { border: 0.5em solid; }
h2 { margin: 0 1em; border-width: 0 0 0.5em 0.5em; padding: 1em; font-weight: bolder; }
ul, li { padding: 0.5em; }
ul { margin: 0 1em; border-width: 0 0.5em 0.5em 0; }
li { list-style: inside decimal; }
li p { display: inline; }
*#no_script { margin: 1em; padding: 1em; background: red; color: palegoldenrod; font-weight: bolder; }
*#no_script a { color: palegoldenrod; }
</style>
<!--[if IE]>
<style type="text/css" media="all">
h1 { zoom: 1; filter: alpha(opacity=80); }
</style>
<![endif]-->

</head>
<body>

<h1>Demo for <a href="http://www.codingforums.com/showthread.php?t=146939">CodingForums.com Thread 146939</a></h1>
<p id="no_script">ECMAScript must be enabled in your browser for this document to work properly. Please enable it or obtain an ECMAScript&#x2010;capable browser such as <a href="http://www.mozilla.com/firefox/">Mozilla Firefox</a>.</p>

<!--[if !IE]>-->
<script type="application/ecmascript" defer="defer">
var d = document;
var r = 0; // random number
var percent_chance_of_100 = 10; // initial 10% chance of 100 and 90% chance of 1 through 99
var p_element = d.getElementById("no_script");
var h2_element = d.createElement("h2");
var ul_element = d.createElement("ul"); // appended later to maintain HTML 4.01 validity
h2_element.appendChild(d.createTextNode("The Results"));
p_element.parentNode.replaceChild(h2_element, p_element);
function output(result) {
var li_element = d.createElement("li");
var p_element = d.createElement("p");
var percent_chance = "";
if (result === 100) {
percent_chance = percent_chance_of_100.toString();
}
else {
percent_chance = ((100 - percent_chance_of_100) / 99).toFixed(2);
}
var message = "The result is " + result.toString() + ". There was a " + percent_chance + " percent chance of receiving this result.";
p_element.appendChild(d.createTextNode(message));
li_element.appendChild(p_element);
ul_element.appendChild(li_element);
if (ul_element.childNodes.length === 1) {
d.getElementsByTagName("body").item(0).insertBefore(ul_element, d.getElementsByTagName("h2").item(0).nextSibling);
}

}
function draw_number() {
r = Math.floor(Math.random() * (100 + 1));
if (r <= percent_chance_of_100) {
r = 100;
output(r);
if (typeof delay !== "undefined") {
window.clearInterval(delay);
}
}
else {
r = Math.floor(Math.random() * (99 + 1));
output(r);
percent_chance_of_100 += 2;
}
}
if (typeof window !== "undefined" && window.setInterval !== undefined && window.clearInterval !== undefined) {
draw_number();
if (r !== 100) {
var delay = window.setInterval(draw_number, 2000);
}
}
else {
do {
draw_number();
}
while (r !== 100);
}
</script>
<!--<![endif]-->
<!--[if IE]>
<script type="text/ecmascript" defer="defer">
var d = document;
var r = 0; // random number
var percent_chance_of_100 = 10; // 10% chance of 100; 90% chance of 1 through 99
var p_element = d.getElementById("no_script");
var h2_element = d.createElement("h2");
var ul_element = d.createElement("ul"); // appended later to maintain HTML 4.01 validity
h2_element.appendChild(d.createTextNode("The Results"));
p_element.parentNode.replaceChild(h2_element, p_element);
function output(result) {
var li_element = d.createElement("li");
var p_element = d.createElement("p");
var percent_chance = "";
if (result === 100) {
percent_chance = percent_chance_of_100.toString();
}
else {
percent_chance = ((100 - percent_chance_of_100) / 99).toFixed(2);
}
var message = "The result is " + result.toString() + ". There was a " + percent_chance + " percent chance of receiving this result.";
p_element.appendChild(d.createTextNode(message));
li_element.appendChild(p_element);
ul_element.appendChild(li_element);
if (ul_element.childNodes.length === 1) {
d.getElementsByTagName("body").item(0).insertBefore(ul_element, d.getElementsByTagName("h2").item(0).nextSibling);
}

}
function draw_number() {
r = Math.floor(Math.random() * (100 + 1));
if (r <= percent_chance_of_100) {
r = 100;
output(r);
if (typeof delay !== "undefined") {
window.clearInterval(delay);
}
}
else {
r = Math.floor(Math.random() * (99 + 1));
output(r);
percent_chance_of_100 += 2;
}
}
if (typeof window !== "undefined" && window.setInterval !== undefined && window.clearInterval !== undefined) {
draw_number();
if (r !== 100) {
var delay = window.setInterval(draw_number, 2000);
}
}
else {
do {
draw_number();
}
while (r !== 100);
}
</script>
<![endif]-->

</body>
</html>

XHTML with PHP:

<?php
ob_start();
header("Content-Type: application/xhtml+xml; charset=UTF-8");
header("Content-Script-Type: application/ecmascript");
header("Content-Style-Type: text/css");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>

<html xml:lang="en-Latn" xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8"></meta>
<meta http-equiv="Content-Script-Type" content="application/ecmascript"></meta>
<meta http-equiv="Content-Style-Type" content="text/css"></meta>
<title>Demo for CodingForums.com Thread 146939 (XHTML)</title>
<meta name="Author" content="Patrick Garies"></meta>
<meta name="Created" content="2008-08-18"></meta>
<meta name="Revised" content="2008-08-19"></meta>
<style type="text/css" media="all"><![CDATA[
* { margin: 0; padding: 0; }
html, h1, h2 { font: 16px/1.2 sans-serif; }
html { background: #ded url("bg_c.png"); color: black; }
h1 { opacity: 0.8; padding: 2em; background: white; font-weight: bolder; }
a { color: black; }
h2, ul { border: 0.5em solid; }
h2 { margin: 0 1em; border-width: 0 0 0.5em 0.5em; padding: 1em; font-weight: bolder; }
ul, li { padding: 0.5em; }
ul { margin: 0 1em; border-width: 0 0.5em 0.5em 0; }
li { list-style: inside decimal; }
li p { display: inline; }
*#no_script { margin: 1em; padding: 1em; background: red; color: palegoldenrod; font-weight: bolder; }
*#no_script a { color: inherit; }
]]></style>

</head>
<body>

<h1>Demo for <a href="http://www.codingforums.com/showthread.php?t=146939">CodingForums.com Thread 146939</a></h1>
<p id="no_script">ECMAScript must be enabled in your browser for this document to work properly. Please enable it or obtain an ECMAScript&#x2010;capable browser such as <a href="http://www.mozilla.com/firefox/">Mozilla Firefox</a>.</p>

<script type="application/ecmascript" defer="defer"><![CDATA[
var d = document;
var XHTML_NS = "http://www.w3.org/1999/xhtml";
var r = 0; // random number
var percent_chance_of_100 = 10; // initial 10% chance of 100 and 90% chance of 1 through 99
var p_element = d.getElementById("no_script");
var h2_element = d.createElementNS(XHTML_NS, "h2");
var ul_element = d.createElementNS(XHTML_NS, "ul");
h2_element.appendChild(d.createTextNode("The Results"));
p_element.parentNode.replaceChild(h2_element, p_element);
d.getElementsByTagNameNS(XHTML_NS, "body").item(0).insertBefore(ul_element, d.getElementsByTagNameNS(XHTML_NS, "h2").item(0).nextSibling);
function output(result) {
var li_element = d.createElementNS(XHTML_NS, "li");
var p_element = d.createElementNS(XHTML_NS, "p");
var percent_chance = "";
if (result === 100) {
percent_chance = percent_chance_of_100.toString();
}
else {
percent_chance = ((100 - percent_chance_of_100) / 99).toFixed(2);
}
var message = "The result is " + result.toString() + ". There was a " + percent_chance + " percent chance of receiving this result.";
p_element.appendChild(d.createTextNode(message));
li_element.appendChild(p_element);
ul_element.appendChild(li_element);

}
function draw_number() {
r = Math.floor(Math.random() * (100 + 1));
if (r <= percent_chance_of_100) {
r = 100;
output(r);
if (typeof delay !== "undefined") {
window.clearInterval(delay);
}
}
else {
r = Math.floor(Math.random() * (99 + 1));
output(r);
percent_chance_of_100 += 2;
}
}
if (typeof window !== "undefined" && window.setInterval !== undefined && window.clearInterval !== undefined) {
draw_number();
if (r !== 100) {
var delay = window.setInterval(draw_number, 2000);
}
}
else {
do {
draw_number();
}
while (r !== 100);
}
]]></script>

</body>
</html>

Deacon Frost
08-19-2008, 07:54 AM
That is EXACTLY what I need.

Care to explain it?

Thank you so much for taking the time to put it all together :o!

Arbitrator
08-19-2008, 08:23 AM
That is EXACTLY what I need.Note that I corrected an error in the code. The previous post has been edited.

I found another error while writing this post. The ul element should be an ol element for semanticís sake. The live versions (only) have been updated with this change.


Care to explain it?At the start, I declare necessary variables and remove the message for users without scripting enabled. I also create ďThe ResultsĒ header.

The function, draw_number, picks randomly between 1 and 100. 1 through 10 is the 10 percent range needed for 100. If the number is 1 through 10, the script ends (with output). Otherwise, a new random draw occurs for 1 through 99, the percent range is increased by two percent, and the function repeats (after output).

Note that there are two code tracks that lead to the draw. The first track is used if setInterval and its friends are supported; this should, generally, be always. The second track is used otherwise; the results will appear instantly in the second track without the two second delay between the creation of new list items. (The second track was what I had originally started coding and didnít want to get rid of it since itís the first time that Iíve found a use for a do while loop. I also have separate tracks since I always test for support of features like setInterval that arenít part of a formal Web standard.)

The function, output, outputs the result into the document as an HTML/XHTML ordered list with paragraphs.

The Internet Explorer version of the script is the same in this particular demo with the exception of the MIME type. (So, you can get away with using a single script for this demo by, say, using a single script element with one of the older MIME types.)

The XHTML version of the script changes some methods into namespace‐aware methods and appends the ol element earlier since thereís no need for validity (i.e., thereís no document type declaration to validate against).

If you have trouble understanding how I edited the document (i.e., createElement, getElementsByTagName, appendChild, etc.), you may want to look up information on the W3C DOM. I figure that this might be the case since youíre still using outdated things like document.write.

Trinithis
08-19-2008, 08:30 AM
Here's a demo using the code I wrote above:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Test</title>
</head>
<body><div>

<div id="output"></div>

<script type="text/javascript">

function output(str) {
var out = document.getElementById("output");
out.appendChild(document.createTextNode(str));
out.appendChild(document.createElement("br"));
}

function genRand(chance) {
var rand = Math.floor( chance >= Math.random() * 100
? Math.random() + 100
: Math.random() * 101
);
var str = "Your number is " + rand + ". You had a " + (100 - chance) + "% chance of losing.";
if(rand >= 100)
output("Success: " + str);
else {
output("Failure: " + str);
setTimeout(function() {
genRand(chance + 2);
}, 2000);
}
}

genRand(10);

</script>
</div></body>
</html>

Deacon Frost
08-19-2008, 08:47 AM
Wow!

Thanks for the explanation. I will probably end up using a combination of both of those.

I figured it'd be much more difficult than those. I can sort of read them, but I'm still very new to javascript, so yeah, it still confuses me.

Most of the knowledge I have of JS stems from w3schools, and other random browsing, so the other functions required were beyond what I had learned.

Now, how would I put either of those into a singular function? Would it simply be easy:

function fullscript(){
<script>
}

Or would I need to break it up?

Basically so I can put it onto an onclick...

Arbitrator
08-19-2008, 08:48 AM
Arbitrator: What's with the PHP codeDeacon Frost is, apparently, familiar with PHP, so I decided to just paste in the raw source. The PHP portion of the code is easy enough to remove, if desired, since itís all in one place.


duplicate JS code (the IE/!IE) in your html file?I create separate script elements due to Internet Explorerís lack of support for the newer application/* MIME types.

When writing demos, I embed scripts (and style sheets) for ease of reading and maintenance (i.e., I maintain one file). When scripts happen to be identical between the sets of conditional comments (which is not that often) you get demos like this one that appear to be very redundant. In a ďrealĒ Web page, I probably would have referenced a single external script like in the following code:


<!--[if !IE>-->
<script type="application/ecmascript" src="script.es"></script>
<!--<![endif]-->
<!--[if IE]>
<script type="text/ecmascript" src="script.es"></script>
<![endif]-->

Of course, if the scripts didnít contain the same content, then I would create and reference two separate external files instead. Each browser would only download one, so there would likely be a decrease in bandwidth usage.

Trinithis
08-19-2008, 08:54 AM
Basically so I can put it onto an onclick

Try this:


var el = ...

el.onclick = function() {
genRand(10);
};

Arbitrator
08-19-2008, 09:03 AM
Now, how would I put either of those into a singular function? Would it simply be easy:

function fullscript(){
<script>
}

Or would I need to break it up?

Basically so I can put it onto an onclick...In my code, you would nest the following code in a function:


if (typeof window !== "undefined" && window.setInterval !== undefined && window.clearInterval !== undefined) {
draw_number();
if (r !== 100) {
var delay = window.setInterval(draw_number, 2000);
}
}
else {
do {
draw_number();
}
while (r !== 100);
}

The new code would look like the following:


function start_computation() {
if (typeof window !== "undefined" && window.setInterval !== undefined && window.clearInterval !== undefined) {
draw_number();
if (r !== 100) {
var delay = window.setInterval(draw_number, 2000);
}
}
else {
do {
draw_number();
}
while (r !== 100);
}
}

(Actually, thatís a bit simplified. Youíd probably want to throw all of the DOM stuff at the beginning (like the ďThe ResultsĒ header creation) into the function too, but what youíd do there depends on your documentís structure.)

To call your function, you might use one of the following:

HTML/XHTML

<element onclick="start_computation();"></element>

W3C DOM2 Events (for everything except Internet Explorer)

element.addEventListener("click", start_computation, false);

Microsoft attachEvent Method (for Internet Explorer; non‐standard)

element.attachEvent("onclick", start_computation);

(Or, as I just noticed Trinithis used:)

element.onclick (non‐standard)

element.onclick = start_computation;

Trinithis
08-19-2008, 09:19 AM
Is element.onclick really non‐standard? I know it comes from way back when, but I thought it was still valid.

Normally I would use the DOM methods, but I opted for simplicity.

Arbitrator
08-19-2008, 09:33 AM
Is element.onclick really non‐standard?Yes, it is non‐standard. DOM2 HTML doesnít have an onclick property; you have to use setAttribute("onclick", value); (via DOM Core) which, of course, doesnít work correctly in Internet Explorer. <element onclick="value"></element> is more standard than element.onclick.


I know it comes from way back when, but I thought it was still valid.Thereís really no such thing as validity in the scripting world.


Normally I would use the DOM methods, but I opted for simplicity.Yeah, I realize that they can be verbose when browser support is factored into the equation.

If I were to use element.onclick, I would test it first since itís a non‐standard feature:


if (element.onclick !== undefined) {
element.onclick = do_something;
}

Of course, thatís just my preference.

Trinithis
08-19-2008, 09:57 AM
Thanks for the info. (For some reason my thanks button isn't working.)

liorean
08-19-2008, 11:00 AM
Yes, it is non‐standard. DOM2 HTML doesn’t have an onclick property; you have to use setAttribute("onclick", value); (via DOM Core) which, of course, doesn’t work correctly in Internet Explorer. <element onclick="value"></element> is more standard than element.onclick.While setAttribute("onclick", value); sets an attribute value, that's the only effect it has on the DOM. In the W3C DOM, setting an attribute has nothing to do with attaching an event handler. As for the DOM0 way of doing it, it may not be a de jure standard, but it's one of the oldest de facto standard that JavaScript has. (In fact, I believe it's part of the JavaScript 1.3 Client reference, which is as close to being a de jure standard as anything before 1999 went on scripting issues).

Deacon Frost
08-20-2008, 04:28 AM
Alright, for coding purposes (so I'm not scrolling so much code) I'm using trin's, but the final document, I'll probably switch since Arb's is less vulnerable.

I've been messing around with this all day, trying to figure it out, and reading it all. I've breathed this code today XD. And I've pretty much worked out all the kinks of it, how to work it, etc. So now it brings me to another new question that results in bugs out the ***!

Here's all the codes I'm using:




This is the original altered with extra functions which are defined in lower code's.



<script type="text/javascript">


function test(){

document.getElementById("output").innerHTML = "";

hideshown('Start');


function output(str) {
var out = document.getElementById("output");
out.appendChild(document.createTextNode(str));
out.appendChild(document.createElement("br"));
}




function genRand(chance) {
var rand = Math.floor( chance >= Math.random() * 100
? Math.random() + 100
: Math.random() * 101
);
var str = "Your number is " + rand + ". You had a " + (100 - chance) + "% chance of losing.";

if(rand >= 100){

output("Success: You successfully retrieve the log!");
showhide('End');
}
else {
output("Failure: You failed to retrieve the log.");
setTimeout(function() {
genRand(chance + 2);
}, 3000);
}
}


genRand(8);
}

</script>





This code is to keep hidden the bottom button on the script, and then display it after the above script returns true.





<script language="javascript">
<!--
var state = 'hidden';

function showhide(layer_ref) {

if (state == 'visible') {
state = 'hidden';
}
else {
state = 'visible';
}
if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref + ".style.visibility = state");
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].visibility = state;
}
if (document.getElementById && !document.all) {
maxwell_smart = document.getElementById(layer_ref);
maxwell_smart.style.visibility = state;
}
}
//-->

function startover(){


hideshown('End');
document.getElementById("output").innerHTML = "The item was added to your inventory!";
showhide('Start');

}

</script>




This is the EXACT same code, flipped around for the top button, so instead of it starting hidden, it hides after it is clicked:






<script type="text/javascript">
<!--
var state2 = 'visible';

function hideshown(layer_ref2) {

if (state2 == 'visible') {
state2 = 'hidden';
}
else {
state2 = 'visible';
}
if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref2 + ".style.visibility = state2");
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref2].visibility = state2;
}
if (document.getElementById && !document.all) {
maxwell_smart = document.getElementById(layer_ref2);
maxwell_smart.style.visibility = state2;
}
}
//-->
</script>




This is the output area:





<div id="Start">
<input type="button" onclick="test()" value="Click Me!">
</div>


<div id="outputs" value="init()"><div id="output"></div></div>






<!-- HIDDEN INFORMATION TO BE SHOWN ONCLICK -->
<div id="End" style="visibility:hidden;">
<input type="button" value="It worked!" onclick="startover()" />
</div></center>

</div>



What the code currently does:


It runs the first time just fine. You click the top button, it disappears, runs the script, and when the script returns true, it displays the bottom button.

Then when you click the bottom button it clears the div output area, and displays the custom text. Then you click the bottom button again to make it disappear, and the top button reappear. When you click the top button again it doesn't disappear, instead it clears the area, and re-runs the script. It also doesn't display the bottom button. You have to click the top button again, it runs the script, and then displays the button like the first time.


If you ask me it's a VERY odd error, here's how it's supposed to run:


The person clicks the top button.
The top button disappears.
The script runs, until it returns true.
When it returns true, the bottom button shows up.
When the user clicks the bottom button, it disappears, it clears output, and puts different text in it, and it makes the top button reappear.

And then the user runs it again like it did the first time.


I appreciate the help guys :D... If I can finish this side-project I'll link to your guys' portfolios or whatever ya need as credit since you've helped so much!

Arbitrator
08-20-2008, 04:36 AM
While setAttribute("onclick", value); sets an attribute value, that's the only effect it has on the DOM. In the W3C DOM, setting an attribute has nothing to do with attaching an event handler.Iím not sure what point youíre trying to make here. The W3C DOM need not define what an attribute does after attachment; thatís where the HTML and XHTML specifications come in.


As for the DOM0 way of doing it, it may not be a de jure standard, but it's one of the oldest de facto standard that JavaScript has.Yes, I realize that itís quite well‐supported. Still, Iíd rather get away from de facto standards and move on to de jure standards when possible; if the de facto standard becomes de jure (as Iím guessing it will in HTML 5), then Iíll consider changing my tune.


(In fact, I believe it's part of the JavaScript 1.3 Client reference, which is as close to being a de jure standard as anything before 1999 went on scripting issues).Itís too bad that itís 2008, Netscape is defunct, and the ECMAScript specification doesnít mention this property.

Anyway, thatís an interesting document that Iíve never seen before. The part on onClick doesnít seem to cover element.onclick though; all I see is a reference to an HTML attribute: ďonClick="handlerText"Ē.

Arbitrator
08-20-2008, 05:37 AM
What the code currently does:


It runs the first time just fine. You click the top button, it disappears, runs the script, and when the script returns true, it displays the bottom button.

Then when you click the bottom button it clears the div output area, and displays the custom text. Then you click the bottom button again to make it disappear, and the top button reappear. When you click the top button again it doesn't disappear, instead it clears the area, and re-runs the script. It also doesn't display the bottom button. You have to click the top button again, it runs the script, and then displays the button like the first time.


If you ask me it's a VERY odd error, here's how it's supposed to run:


The person clicks the top button.
The top button disappears.
The script runs, until it returns true.
When it returns true, the bottom button shows up.
When the user clicks the bottom button, it disappears, it clears output, and puts different text in it, and it makes the top button reappear.

And then the user runs it again like it did the first time.Problem:

click top: hides top, shows bottom
click bottom: hides top, shows bottom (redundant)
click bottom: shows top, hides bottom
click top: shows top, hides bottom (redundant)
click top: hides top, shows bottom
repeat

I donít really see the point of showhide and hideshown when you can use something so much simpler:


var d = document;
var Start = d.getElementById("Start");
var End = d.getElementById("End");
function set_view(element, view) {
element.style.visibility = view;
}

// Example Invocations of |set_view|
set_view(Start, "hidden");
set_view(End, "visible");

Deacon Frost
08-20-2008, 06:08 AM
Thanks for the tidy! It really eliminated a lot O.O...

However, the bottom button doesn't work properly for some reason:

full code:


<script type="text/javascript">


function startover(){


set_view(End, "hidden");
d.getElementById("output").innerHTML = "The item was added to your inventory!";
set_view(Start, "visible");

}

function test(){

var d = document;
var Start = d.getElementById("Start");
var End = d.getElementById("End");
function set_view(element, view) {
element.style.visibility = view;
}

d.getElementById("output").innerHTML = "";

set_view(Start, "hidden");


function output(str) {
var out = document.getElementById("output");
out.appendChild(document.createTextNode(str));
out.appendChild(document.createElement("br"));
}




function genRand(chance) {
var rand = Math.floor( chance >= Math.random() * 100
? Math.random() + 100
: Math.random() * 101
);
var str = "Your number is " + rand + ". You had a " + (100 - chance) + "&#37; chance of losing.";

if(rand >= 100){

output("Success: You successfully retrieve the log!");
set_view(End, "visible");
}
else {
output("Failure: You failed to retrieve the log.");
setTimeout(function() {
genRand(chance + 2);
}, 0);
}
}


genRand(8);
}



</script>




The part that isn't executing properly is:




function startover(){


set_view(End, "hidden");
d.getElementById("output").innerHTML = "The item was added to your inventory!";
set_view(Start, "visible");

}







Again, the document:



<div id="Start">
<input type="button" onclick="test()" value="Click Me!">
</div>


<div id="outputs" value="init()"><div id="output"></div></div>






<!-- HIDDEN INFORMATION TO BE SHOWN ONCLICK -->
<div id="End" style="visibility:hidden;">
<input type="button" value="It worked!" onclick="startover()" />
</div>




The code works the first try:

1. Click top button.
2. Top Button Disappears.
3. Text Loads.
4. Bottom button appears.
5. Click bottom button.
6. Bottom button disappears.
7. Text changes to chosen.
8. Top button reappears.

_______
9. Click top button.
10. Text loads.
11. Bottom button appears.
12. Click bottom button.
13. Text changes to chosen.
14. Click bottom button, again.
15. Bottom button disappears.
16. Top button reappears.
---------

^repeat^

Arbitrator
08-20-2008, 06:17 AM
The part that isn't executing properly is:




function startover(){


set_view(End, "hidden");
d.getElementById("output").innerHTML = "The item was added to your inventory!";
set_view(Start, "visible");

}The problem is probably because youíre trying to reference End, Start, and set_view; these are currently all local to the function test. Try moving the following code out of the function test to make it global:


<script type="text/javascript">
var d = document;
var Start = d.getElementById("Start");
var End = d.getElementById("End");
function set_view(element, view) {
element.style.visibility = view;
}
function start_over() { // Ö }
function test() { // Ö }
</script>

Deacon Frost
08-20-2008, 06:33 AM
I must be doing something wrong?

It regressed XD.

http://ispikedthepunch.com/game/index2.php


^demo

Arbitrator
08-20-2008, 07:10 AM
I must be doing something wrong?The following two lines…


var Start = d.getElementById("Start");
var End = d.getElementById("End");

… reference two elements before they exist. You need to move that code to a location in the source after the reference in the code (e.g., at the end of the body element as in my demo).

Alternatively, you can adjust my code so that it works more similarly to the code that it replaced:


var d = document;
var Start = d.getElementById("Start");
var End = d.getElementById("End");
function set_view(element, view) {
element.style.visibility = view;
}

… would become…


var d = document;
function set_view(ID, view) {
d.getElementById(ID).style.visibility = view;
}

… and the script would not need to be moved.

The code would be invoked the same as it was before except that the first parameter would be a string (e.g., set_view("Start", "hidden");.

liorean
08-20-2008, 09:15 PM
I’m not sure what point you’re trying to make here. The W3C DOM need not define what an attribute does after attachment; that’s where the HTML and XHTML specifications come in.The HTML spec tells implementations what to do with the serialisation. The DOM tells us how to deal with the node tree. The HTML4.01 spec does not go into any detail on this issue, more than referring to the DOM WG's work. The DOM2HTML spec doesn't tell anything on the issue, either. The DOM2Events spec does tell us something about it, but it goes so shallow into the issue that nothing is actually more than hinted. It does for example not address when an attribute is set through the DOM at all. All in all, there is no spec that actually deals with events in markup to such a level that any two implementors would actually be able to independently produce compatible implementations.

In any case, the way to add an event in the DOM is not by adding an attribute. The Core DOM functionality of elm.setAttribute does not cover attaching event listeners to elements, or for that matter any other effect than setting the attribute with a certain name to a certain string. The DOM does in no case I can think of right off the top of my head say that node manipulations after a tree has been built are subject to the same side effectual handling as when parsing the serialisation.

The DOM does however provide separate functionality for the various components of the parsing handling in this as well as in other cases. The serialisation <elm onevent="blah();"></elm> does thus seem to be intended to be equivalent to the parser doing the internal equivalent of the two separate actions:
- Core DOM elm.setAttibute('onevent','blah();')
- DOM2Events elm.addEventListener('event',new Function('event','blah();'),false);

Nowhere in the DOM spec or in the HTML spec does anything indicate that the side effect in the parser is intended to also be a side effect of direct node manipulation.

Yes, I realize that it’s quite well‐supported. Still, I’d rather get away from de facto standards and move on to de jure standards when possible; if the de facto standard becomes de jure (as I’m guessing it will in HTML 5), then I’ll consider changing my tune.I guess I'm more pragmatic about things like this. (I wasn't always...) If something has de facto support in all browsers, I consider that many times better than if something has de jure support in fewer browsers.
It’s too bad that it’s 2008, Netscape is defunct, and the ECMAScript specification doesn’t mention this property.That's because the ECMAScript spec is a pure language specification, while the JavaScript Client spec is a language+environment specification. Some things that were de facto standards and well documented and supported have become worth much less in many eyes because they were never caught up in any single of the de jure standardisations that happened. You can't use ECMAScript in a browser in a meaningful way at all without using thing that are pure de facto standards, like the window object and everthing that you can reach from it.

Arbitrator
08-21-2008, 06:51 AM
The DOM does in no case I can think of right off the top of my head say that node manipulations after a tree has been built are subject to the same side effectual handling as when parsing the serialisation.

Ö

Nowhere in the DOM spec or in the HTML spec does anything indicate that the side effect in the parser is intended to also be a side effect of direct node manipulation.I think that these things are more or less implied even if they arenít specified exactly. The DOM would be useless if updating it didnít dynamically update the document.


You can't use ECMAScript in a browser in a meaningful way at all without using thing that are pure de facto standards, like the window object and everthing that you can reach from it.Unless thereís something that Iím missing, Iíd have to disagree. Iíve written many scripts that donít use the window object at all. In fact, I could have avoided it here, too, in the primary script track by using document.defaultView instead (although I would still have had to use its non‐standard methods setInterval and clearInterval) or not at all if the time delay were not deemed necessary.

liorean
08-21-2008, 09:47 AM
I think that these things are more or less implied even if they aren’t specified exactly. The DOM would be useless if updating it didn’t dynamically update the document.The Core DOM does exactly that - update the document. It does NOT attach events, change styles etc. That's what we have DOM2Events and DOM2Style for.
Unless there’s something that I’m missing, I’d have to disagree. I’ve written many scripts that don’t use the window object at all. In fact, I could have avoided it here, too, in the primary script track by using document.defaultView instead (although I would still have had to use its non‐standard methods setInterval and clearInterval) or not at all if the time delay were not deemed necessary.The only reason you can even get hold of document is because the de facto standard object window is merged with the ECMAScript global object. The only objects you could actually reach if not for window are the ECMAScript standard library objects, and those doesn't get you anywhere by themselves. That's how fundamental some things that were never part of a web standard really are to scripting.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum