Javascript 4-image slideshow w/ arrays & setTimeout - javascript

<script type=text/javascript>
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
for(var i = 0, l = topLeftImages.length; i < l; i++)
{
setTimeout(function()
{
document.getElementById('myimage1').src = "images\\" + "op.jpg";
document.getElementById('myimage2').src = "images\\" + topRightImages[i];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[i];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[i];
}, 10000);
}
</script>
Associated HTML:
<img id="myimage1" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage2" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage3" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage4" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
This code is meant to show four images, and every 10 seconds, switch all four images simultaneously, going through all of my images in my four arrays. The images are in the images/ directory above my HTML file that contains this code. For testing purposes, I changed myimage1 to change to op.jpg only. This works and correctly shows op.jpg. However, when querying the arrays, instead of the file names, I get undefined. That is problem number one.
Problem number two, when I change my for loop to a more normal looking one like:
for(var i = 0; i < l2; i++)
The script stops working entirely (doesn't show op.jpg and doesn't even try to change the images)... what the hell!
I'm using Firefox and Google Chrome for testing purposes.

I suggest something like that instead:
<script type=text/javascript>
$(document).ready(function () {
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
var i = 0;
var max = 12;
setInterval(function()
{
var index = i % max;
document.getElementById('myimage1').src = "images\\" + topLeftImages[index];
document.getElementById('myimage2').src = "images\\" + topRightImages[index];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[index];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[index];
i++;
}, 10000);
});
</script>
jsFiddle with some example images http://jsfiddle.net/ApfJz/8/

Related

Cannot read property 'setAttribute' of null - Javascript

I have seen a couple of questions posted with this error on here and having seen some of the answers I noticed the general consensus is that it is caused due to the DOM not being created yet. I have tried a few different solutions to fix it such as moving my script to immediately prior to the tag, using log outputs before and after the image creation in order to ensure the object is actually being created correctly but nothing has resolved my issue. I am new to Javascript so it might be something obvious I am missing?
var dice = [6, 6, 6, 6, 6];
function rollDice() {
for (var i = 0; i < dice.length; ++i) {
var num = Math.floor(Math.random() * 6 + 1);
dice[i] = 1;
document.write(dice[i] + "<br>");
}
for (var i = 0; i < dice.length; ++i) {
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value];
}
document.getElementById("dice_1").setAttribute("src", path)
}
<html>
<head>
<meta charset="utf-8">
<title>Project 1</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1> This is a javascript application</h1>
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<div>
<img id="dice_1" src="images/dice 1.png">
<img id="dice_2" src="images/dice 1.png">
<img id="dice_3" src="images/dice 1.png">
<img id="dice_4" src="images/dice 1.png">
<img id="dice_5" src="images/dice 1.png">
</div>
<input id="but" type="button" onclick="rollDice()" value="Roll Dice.">
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
Since you're using document.write after the document has loaded, it's clearing the entire document (due to document.open() being called). Therefore, your img elements do not exist for setAttribute to be run against them. Try the following (note the index corrections that are needed due to array indexing starting at zero):
var dice = [6,6,6,6,6];
var results;
var resultsContainer = document.querySelector('.results');
function rollDice(){
// clear results array
results = [];
for(var i =0; i<dice.length; ++i){
var num = Math.floor(Math.random()*6 +1);
dice[i] = num;
results.push(dice[i]);
}
for(var i =0; i< dice.length; ++i){
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3.png", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value - 1];
document.getElementById("dice_"+ (i + 1)).setAttribute("src",path);
}
// convert results array to text with <br> between them
var resultsStr = results.join("<br>");
// display results as text to page
resultsContainer.innerHTML = resultsStr;
}

HTML and JS debugging with YQL query

Can anyone help me debug this? It's supposed to update the thermometer with the value of the current fundraising amount. It was working prior to the YQL html table no longer being supported. I updated the REST query based on an answer I found here and now see the data, but it's not updating the thermometer. Any advice is appreciated!
<div style="text-align:center;"><img id="thermometer" border="0" src="http://www.coolfundraisingideas.net/thermometer/thermometer.php?currency=dollar&goal=100&current=25&color=red&size=large">
<p style="font-size:.8em; color:#999">Provided by CoolFundraisingIdeas.net</p>
</div>
<script>
function therData() {
var current = arguments[0].query.results.body.root.eventfundraisingtotals_collection.eventfundraisingtotals.eventverifiedtotalcollected;
var goal = arguments[0].query.results.body.root.eventfundraisingtotals_collection.eventfundraisingtotals.eventverifiedfundraisinggoal;
document.getElementById('thermometer').src = 'http://www.coolfundraisingideas.net/thermometer/thermometer.php?currency=dollar&goal=' + goal + '&current=' + current + '&color=red&size=large';
document.getElementsByTagName('head')[0].removeChild(document.getElementById('therScript'));
}
var therScript = document.createElement('script');
therScript.setAttribute('id', 'therScript');
therScript.src =
"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D'http%3A%2F%2Fmy.e2rm.com%2Fwebgetservice%2Fget.asmx%2FgetEventFundraisingTotals%3FeventID%3D223256%26loginOrgID%3DASOSEW%26locationExportID%3D%26Source%3D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=therData";
document.getElementsByTagName('head')[0].appendChild(therScript);
</script>
This is a change to your script, but with some crafty JavaScript, it's working.
Working fiddle: https://jsfiddle.net/kay6jpqx/
HTML:
<div style="text-align:center;">
<a href="https://www.coolfundraisingideas.net/" alt="Fundraising Thermometer">
<img id="thermometer" border="0" src="https://www.coolfundraisingideas.net/thermometer/thermometer.php?currency=dollar&goal=100&current=50&color=red&size=large"></a>
<p style="font-size:.8em; color:#999">Provided by CoolFundraisingIdeas.net
</p>
</div>
JavaScript:
function therData(arguments){
//console.log(arguments.query.results.result);
var res = arguments.query.results.result;
//get the current amount from the result
var startPos = res.indexOf("eventverifiedtotalcollected")+28;
var endPos = res.indexOf("/eventverifiedtotalcollected")-1;
var evtVerTotal = res.substring(startPos, endPos);
console.log(evtVerTotal);
//get the goal amount from the result
startPos = res.indexOf("eventverifiedfundraisinggoal")+29;
endPos = res.indexOf("/eventverifiedfundraisinggoal")-1;
var evtVerGoal = res.substring(startPos, endPos);
console.log(evtVerGoal);
var current = evtVerTotal;
var goal = evtVerGoal
document.getElementById('thermometer').src = 'http://www.coolfundraisingideas.net/thermometer/thermometer.php?currency=dollar&goal=' + goal + '&current=' + current + '&color=red&size=large';
}
var therScript = document.createElement('script');
therScript.setAttribute('id', 'therScript');
therScript.src = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D'http%3A%2F%2Fmy.e2rm.com%2Fwebgetservice%2Fget.asmx%2FgetEventFundraisingTotals%3FeventID%3D223256%26loginOrgID%3DASOSEW%26locationExportID%3D%26Source%3D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=therData";
document.getElementsByTagName('head')[0].appendChild(therScript);

Pulling both values from 2d array but only showing one

Hi I'm attempting to pull only the first word in the array I've built — and then on click of "flip" — show the antonym it's paired with. i.e. pull 0 and 1 but only show 0 until a button is clicked (then have 0 switch out for 1). The code below works fine, but as of right now, it's pulling and appending both words to #input.
Here's my JS:
var words = [];
words[0] = ['Budding','Accomplished'];
words[1] = ['Curious','Certain'];
words[2] = ['Realistic','Idealistic'];
words[3] = ['Practicle','Imaginative'];
function random_sort () {
return (0.5 - Math.random() );
}
words.sort(random_sort);
var i = 0,
n = words.length;
$("#forward").data('dir', 1);
$("#back").data('dir', -1);
$("#forward, #back").on('click', function() {
i = (i + $(this).data('dir') + n) % n;
$("#input").hide().html(words[i]).fadeIn(100);
$(words[i][1]).hide();
});
$("#back").trigger('click');
and my html:
<object id="back" type="image/svg+xml" data="images/arrow.svg"></object>
<p id="input"></p>
<object id="forward" type="image/svg+xml" data="images/arrow.svg"></object>
<img id="flip" src="images/fliptext.svg">
Any help is much appreciated. Thanks!
Your issue is $("#input2").hide().html(words[i]).fadeIn(100); specifically html(words[i]) which is equal to html(['Budding','Accomplished']) and will concatenate the array before adding it to the html.
Change that to $("#input2").hide().html(words[i][0]).fadeIn(100); where words[i][0] is specifically selecting the word at the first index in the array.
var words = [];
words[0] = ['Budding','Accomplished'];
words[1] = ['Curious','Certain'];
words[2] = ['Realistic','Idealistic'];
words[3] = ['Practicle','Imaginative'];
var i=0;
$("#input").hide().html(words[i]).fadeIn(100);
$("#input2").hide().html(words[i][0]).fadeIn(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong>Wrong</strong><div id="input"> </div><br>
<strong>Right</strong><div id="input2"> </div>

Need help creating a button to activate a javascript function

This is my script, I am trying to make a button randomize the images instead of me having to press the refresh button. What exactly do I need to code the button as to make this work?
My code
I think I am confused on what my function name is? I had a lot of help creating this so I'm a bit lost on what to do as far as the button is. I've created a button and I've tried plugging in multiple things for the "onclick" but nothing works.
<!doctype html>
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
(function () {
var theImages = [{
src: "winry doe.gif",
width: "480",
height: "270"
}, {
src: "WINRY WINK.gif",
width: "500",
height: "484"
}, {
src: "winry getting hugged.gif",
width: "500",
height: "205"
},
{
src: "winry getting mad.gif",
width: "500",
height: "292"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
<form>
<input type="button" value="More Winry" onclick="">
</form>
</body>
</html>
Just add :
function randomImage() {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
and to the button onclick add:
<input type="button" value="More Winry" onclick="randomImage()">
EDIT
To replace existing image:
function randomImage() {
var newImage = getRandomImage();
console.log(newImage);
var img = document.getElementsByTagName('img').remove();
document.body.appendChild(newImage);
};
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
add those function instead.
Credits to JavaScript: remove element by id
also, no need of JQuery in functions so JQuery tag is useless.
You can also use similar to this (as long as the img's have that class). Using the prototype method described by Edan Feiles answer
the button html:
<form>
<input id="imageButton" type="button" value="More Winry" />
</form>
and the JS:
var button = document.getElementById("imageButton");
button.onclick = function() {
var newImage = getRandomImage();
console.log(newImage);
document.getElementsByClassName("atvi-image-image").remove();
document.body.appendChild(newImage);
};
or you can use what Edan Feiles said and just add this line to the function:
document.getElementsByClassName("atvi-image-image").remove();
before adding the new random image.

I have a JS script in my php file, and it does not seem to be executing

This started after I converted this same script which was previously laid out in PHP to JS (I tried to change all the syntax.)
I have tried running it how it is within the php file and it didn't work :
<html>
<head>
<title>Learn | A Level Scientist</title>
<link rel="shortcut icon" href="http://www.iconj.com/ico/f/0/f0ghi1ksdc.ico" type="image/x-icon" />
<style>
#menubar {;color:white;font-size:100%;padding-top:5px;padding-bottom:5px;
border-radius:5px;margin-top: 1%;margin-bottom:1%;margin-left:4%;margin-right:4%; background: rgba(0,73,126,0.6);}
span {margin-left:2.5%;margin-right:2.5%;}
#mainsection {background: rgba(0,73,126,0.6);color:white;margin-left:4%;margin-right:4%;border-radius:5px;padding-left:20px;padding-right:20px;padding-bottom:0.5%;text-align:center;}
body {background:radial-gradient(#00477C,#002E4F);}
#horizsep {width:100%;text-align:center;color:white;padding-top:0%;padding-bottom:0%;margin:0px}
#copyright{text-align:center;}
#welcomemsg {font-size:30px;margin:0px;padding:0px}
#surroundmid{font-size:26px; padding-bottom:160px;}
#start_learning:hover {width:155px;font-size:22px;color:white;background-color:#5288AB;border-width:0px;border-radius:5px;}
#tube_part {background-color:#DB2625;margin:0%;}
#you_part {margin:0%;color:black;border-radius:30px;text-align:center}
#fb_part {background-color:#3B5998;color:white;margin:0%;text-align:center}
#acebook_part {background-color:#3B5998;margin:0%}
a{color:white; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:clicked {color: white; underline:none}
*.menubar {border-width:0px;border-radius:1px;background:rgba(0,0,0,0.1);color:white;}
*.menubar:hover{color:white;background-color:#5288AB;border-width:0px;border-radius:1px;}
#loginform {display:inline-block;margin:0px}
#chembutton {width:30%;height:10%;font-size:40px;color:white;background:rgba(17,214,118,0.3);border-width:0px;border-radius:5px;}
#chembutton:hover {width:32%;height:11%;font-size:45px;color:white;background:rgba(17,214,118,0.5);border-width:0px;border-radius:5px;}
#chembutton:active {width:33%;height:12%;font-size:45px;color:white;background:rgba(17,214,118,0.7);border-width:0px;border-radius:5px;}
#ytvid {margin-top:0%;margin-bottom:4.7%}
#video_navigation_next {width:40%;display:inline-block;}
#video_navigation_previous {width:40%;display:inline-block;}
#interface {display:block;width:900px;height:500px;background:rgba(0,46,79,0.4);margin:auto;border-radius:5px;margin-top:5px;margin-bottom:20px;vertical-align:top;}
#output{width:550px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;vertical-align:top;font-size:18px}
#input{width:250px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;margin-left:0px;vertical-align:top;}
#useranswer {margin-top:40px}
#helpsection {margin:10%}
</style>
</head>
<body>
<section>
<?php
include 'C:\xampp\htdocs\ALevelScientistTesting\menubar.php' ;
?>
<div id="mainsection">
<div id="welcomemsg"><strong><u> Working out Relative Formula/Molecular Masses </u></strong></div><br>
<div id="video_navigation_previous"><br><span id="nextvid"> <!-- <= Go to the Previous Exercise --> <span></div>
<div id="video_navigation_next"><br><span id="nextvid"> Go to the Next Exercise => <span></div>
<div id="interface">
<div id="output">
<?php
//echo 'The '.$CoMo.' : '.$SubName[$FormNo].' Has a Relative '.$FoMo.' Mass of : '.$x;
//echo '<br> Work out the Relative '.$FoMo.' Mass of the '.$CoMo.' : '.$SubName[$FormNo] ;
?>
<script type="text/javascript">
document.write('The Program got to here...');
//The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements.
var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon");
var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn");
var ElementsRAM = new Array("1.0","6.9","23.0","39.1","85.5","132.9","223","9.0","24.3","40.1","87.6","137.3","226","45.0","88.9","138.9","227","47.9","91.2","178.5","261","50.9","92.9","180.9","262","52.0","95.9","183.8","266","54.9","98","186.2","264","55.8","101.1","190.2","277","58.9","102.9","192.2","268","58.7","106.4","195.1","271","63.5","107.9","197.0","272","65.4","112.4","200.6","10.8","27.0","69.7","114.8","204.4","12.0","28.1","72.6","118.7","207.2","14.0","31.0","74.9","121.8","209.0","16.0","32.1","79.0","127.6","209","19.0","35.5","79.9","126.9","210","4.0","20.2","39.9","83.8","131.3","222");
// The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas.
var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8");
var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate");
var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>");
// The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas.
var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2");
var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene");
var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>");
//The following part is the section where the specific Formula will be randomly selected for the questions.
var MCselection = Math.floor(Math.random()*2);
document.write(MCselection);
if(MCselection == 0) {
var Formula = CompoundsFormula;
var Name = CompoundsName;
var SubName = SubCompoundsArray;
var CoMo = 'Compound';
var FoMo = 'Formula';
} else {
var Formula = MoleculesFormula;
var Name = MoleculesName;
var SubName = SubMoleculesArray;
var CoMo = 'Molecule';
var FoMo = 'Molecular';
}
var FormNo = Math.floor(Math.random()*30);
var Form = Formula[FormNo];
var FormName = Name[FormNo];
var FormSub = SubName[FormNo];
var ElementSub = new Array();
var FoRAM = new Array();
var ElemProduct = new Array();
// Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length)
// Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise.
var l = 0;
var y = 0;
// The following Code is going to strip away the elements and each corresponding number of moles
// of each element per unit compound/molecule into separate arrays.
while (l < Form.length)) {
if(Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1) || !isNaN(Form.substr(l+1,1))) {
if (!isNaN(Form.substr(l+1,1))) {
Element[y] = Form.substr(l,1);
if (!isNaN(Form.substr(l+2,1))) {
ElementSub[y] = Form.substr(l+1,2);
l++;
l++;
} else {
ElementSub[y] = Form.substr(l+1,1);
l++;
}
} else {
Element[y] = Form.substr(l,2);
if (!isNaN(Form.substr(l+2,1))) {
if (!isNaN(Form.substr(l+3,1))) {
ElementSub[y] = Form.substr(l+2,2);
l+=3;
} else {
ElementSub[y] = Form.substr(l+2,1);
l+=2;
}
} else {
ElementSub[y] = 1;
l++;
}
}
} else {
Element[y] = Form.substr(l,1);
ElementSub[y] = 1;
}
l++;
y++;
}
// this resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// The following Code Identifies The Different Elements Present in the Array.
while(x < Element.length) {
while(l < ElementsSym.length) {
if (ElementsSym[l]==Element[x]) {
FoRAM[x] = ElementsRAM[l];
}
l++;
}
l = 0;
x++;
}
// this also resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// This find the product of each element multiplied by the number of moles present per mole of the formula.
while(l<Element.length) {
ElemProduct[l] = FoRAM[l]*ElementSub[l];
// echo '<br>';
l++;
}
// This finds the total of all the molar elemental products b adding up the values in an array.
//x = array_sum(ElemProduct);
var n = 0;
var sum = 0;
while(n<ElemProduct.length) {
sum += ElemProduct[n];
n++;
}
document.write("The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum );
// The following Line Presents the Information.
</script>
<script type="text/javascript">
</script>
<br><hr>
</div>
<div id="input">
<form id="useranswer">
Enter Your Answer Here<br>
<input type="text" id="useranswer"><br>
<input type="submit" id="usersubmit" value="Check Answer">
</form>
<div id="helpsection">
<hr><br>
Not sure what Relative Formula mass is? <br>
<a>Click Here.</a> <br>
Not sure what Relative Molecular mass is?<br>
<a>Click Here.</a>
<br>
<hr>
<br>
Haven't learned how to work this out yet? <br>
<a>Click Here.</a>
</div>
</div>
</div>
<hr>
<span id="copyright"> Copyright A Level Scientist 2014 | All rights reserved. <span>
</div>
</section>
</body>
</html>
When I run this code at the moment, the result looks like this :
http://postimg.org/image/6993cuaqb/
Can someone please explain to me what is wrong with the code at the moment ! Thank you :)
---EDIT /
This is my new script, it kind of works, but does not. If someone would kindly test it you may get an insight into what i'm talking about (NAN, Long decimals.). When you're testing it, refresh multiple times and look at what happens.
New Script :
<html>
<head></head>
<body>
<script>
//The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements.
var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon");
var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn");
var ElementsRAM = new Array(1.0,6.9,23.0,39.1,85.5,132.9,223,9.0,24.3,40.1,87.6,137.3,226,45.0,88.9,138.9,227,47.9,91.2,178.5,261,50.9,92.9,180.9,262,52.0,95.9,183.8,266,54.9,98,186.2,264,55.8,101.1,190.2,277,58.9,102.9,192.2,268,58.7,106.4,195.1,271,63.5,107.9,197.0,272,65.4,112.4,200.6,10.8,27.0,69.7,114.8,204.4,12.0,28.1,72.6,18.7,207.2,14.0,31.0,74.9,121.8,209.0,16.0,32.1,79.0,127.6,209,19.0,35.5,79.9,126.9,210,4.0,20.2,39.9,83.8,131.3,222);
// The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas.
var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8");
var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate");
var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>");
// The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas.
var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2");
var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene");
var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>");
//The following part is the section where the specific Formula will be randomly selected for the questions.
var MCselection = Math.floor(Math.random()*2);
if(MCselection === 0) {
var Formula = CompoundsFormula;
var Name = CompoundsName;
var SubName = SubCompoundsArray;
var CoMo = 'Compound';
var FoMo = 'Formula';
} else {
var Formula = MoleculesFormula;
var Name = MoleculesName;
var SubName = SubMoleculesArray;
var CoMo = 'Molecule';
var FoMo = 'Molecular';
}
var FormNo = Math.floor(Math.random()*30);
var Form = Formula[FormNo];
var FormName = Name[FormNo];
var FormSub = SubName[FormNo];
var ElementSub = new Array();
var FoRAM = new Array();
var ElemProduct = new Array();
var Element = new Array();
// Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length)
// Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise.
var l = 0;
var y = 0;
// The following Code is going to strip away the elements and each corresponding number of moles
// of each element per unit compound/molecule into separate arrays.
while (l <= Form.length) {
if((Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1)) || (!isNaN(Form.substr(l+1,1)))) {
if (!isNaN(Form.substr(l+1,1))) {
Element[y] = Form.substr(l,1);
if (!isNaN(Form.substr(l+2,1))) {
ElementSub[y] = Form.substr(l+1,2);
l++;
l++;
} else {
ElementSub[y] = Form.substr(l+1,1);
l++;
}
} else {
Element[y] = Form.substr(l,2);
if (!isNaN(Form.substr(l+2,1))) {
if (!isNaN(Form.substr(l+3,1))) {
ElementSub[y] = Form.substr(l+2,2);
l+=3;
} else {
ElementSub[y] = Form.substr(l+2,1);
l+=2;
}
} else {
ElementSub[y] = 1;
l++;
}
}
} else {
Element[y] = Form.substr(l,1);
ElementSub[y] = 1;
}
l++;
y++;
}
document.write(Element);
// this resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// The following Code Identifies The Different Elements Present in the Array.
while(x < Element.length) {
while(l < ElementsSym.length) {
if (ElementsSym[l]==Element[x]) {
FoRAM[x] = ElementsRAM[l];
}
l++;
}
l = 0;
x++;
}
// this also resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// This find the product of each element multiplied by the number of moles present per mole of the formula.
while(l<Element.length) {
ElemProduct[l] = FoRAM[l]*ElementSub[l];
// echo '<br>';
l++;
}
// This finds the total of all the molar elemental products b adding up the values in an array.
//x = array_sum(ElemProduct);
var n = 0;
var sum = 0;
while(n<ElemProduct.length) {
sum += ElemProduct[n];
n++;
}
document.write("<br> The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum );
// The following Line Presents the Information.
</script>
</body>
</html>
can someone please point me in the right direction as to why this is happening. Thank you.
You have an error on your JS code. On line 125 you have close a bracket too "while (l < Form.length)) {". Fix it by deleting one and try the code

Categories