HTML - Cannot set property 'src' of undefined - javascript

This is my code, I am trying to do an animation with 8 pictures, I was thinking first that the error is because the images are .jpg, but i tryed even converting them to .gif format and the code still did not work, When I try to run the code, i get an error saying: "Cannot set property 'src' of undefined", I don't see any mistakes in the code, i tryed looking at it multiple times, please if someone can help, thanks.
G:\Year 2\OOD - object oriented development\Webpages\Assignment\Explosion
<script>
var explosion = new Array(8);
var c = 0;
var startExplode;
var i = 0;
explosion[0] = 'ex1.jpg'
explosion[1] = "ex2.jpg"
explosion[2] = "ex3.jpg"
explosion[3] = "ex4.jpg"
explosion[4] = "ex5.jpg"
explosion[5] = "ex6.jpg"
explosion[6] = "ex7.jpg"
explosion[7] = "ex8.jpg"
function explode()
{
if(c == 7 | (i > 0 & i <= 1))
{
c = 0;
}
else
{
c++;
document.animation.src = explosion[c];
}
}
</script>
<body>
<form>
<img src ="ex1.jpg" name = "explosion" position = "fixed">
<input type="button" name="startExplode" value="explode"
onClick="startExplode=setInterval('explode()',20);">
</form>
</body>
</html>

There are a couple of problems with the code:
In the function, the AND and OR operators are doubled, not singles:
if(c == 7 | (i > 0 & i <= 1))
SHOULD BE:
if(c == 7 || (i > 0 && i <= 1))
NEXT, you are not referring to the image tag properly, so the SRC will not update, in addition, the image is call "explosion", not "animation", at least in your HTML. Also, if you give the image tag an ID, you can refer to the ID (much easier).
So the code:
document.animation.src = explosion[c];
<img src ="ex1.jpg" name = "explosion" position = "fixed">
SHOULD BE:
document.getElementById("explosion").src=explosion[c];
<img src="ex1.jpg" name="animation" position="fixed" id="explosion">
I hope this helps!

Related

Issue with Revealing Individual Images & Ending Loop

Since my last question, I've decided to reveal images individually. However, now I'm having an issue with the sequence. With what I've written so far, it seems that my second needed image (stack2.PNG) appears before the first (stack1.PNG). Also, I'm not too sure how to go about ending the function after the final image (stack3.PNG).
Here's what I have so far:
<body>
<input type=button value="Produce Stipends" onclick="nextStack()"/>
<img id="stipends" src="nostack.PNG">
</body>
<script>
var stipends = document.getElementById("stipends");
var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"];
var currentStack = 0;
stack.forEach(function(src) {
new Image().src = src;
});
function nextStack() {
currentStack++;
currentStack > 2 && (currentStack = 0);
stipends.src = stack[currentStack];
}
</script>
Also, if it's not too much to ask, how would I go about changing the name of the button once the sequence is over and linking to another page.
Thanks in advance!
Run the below code if you want to output a single index of the stack array on each click.
EDIT: Included comments in code.
var stipends = document.getElementById("stipends");
var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"];
//currentStack = 0 starts the index at 0
//we will use this to iterate over the array in sequential order starting with the first item
var currentStack = 0;
function nextStack() {
//declare array length as a var
var len = stack.length;
//on click, check if currentStack value is less than len
if(currentStack < len){
//console log the item in the stack array that has a matching index
console.log(stack[currentStack]);
//apply the same output as image source
stipends.src = stack[currentStack];
//continue adding to the currentStack for the next loop until finished
currentStack++;
}
}
<input type=button value="Produce Stipends" onclick="nextStack()" />
<img id="stipends" src="nostack.PNG">
Is this what you're trying to do?
var stipends = document.getElementById("stipends");
var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"];
var currentStack = 0;
function nextStack() {
currentStack++;
stipends.src = stack[currentStack];
if (currentStack > stack.length) {
currentStack = 0;
}
}
<input type="button" value="Produce Stipends" onclick="nextStack()"/>
<img id="stipends" src="nostack.PNG">

What is the correct way to put a HTML element into a variable?

I need this code for an automated slideshow on a page.
I have tried changing up the variables.
HTML
JavaScript
<img class="container" id="c1" >
<img class="container" id="c2">
<img class="container" id="c3">
<p class="dot" id="d3"></p>
<p class="dot" id="d2"></p>
<p class="dot" id="d1"></p>
var i;
let slide;
let dot;
function plusSlide()
{
for (i = 3; i >= 0; i--)
{
slide = document.getElementById("c" + i);
dot = document.getElementById("d" + i);
if (i == 3)
{
slide.id = "c" + 0;
dot.id = "d" + 0;
}
else
{
slide.id = "c" + (i + 1);
dot.id = "d" + (i + 1);
}
}
setTimeout(plusSlide, 5000);
}
plusSlide();
The result is correct, but at the variables it says: Parsing Error: Unexpected Token slide
Ok so I am using this for a slideshow with three slides, c are the pictures and d are the dots, I am taking the elements with these ids and I am changing them. I use CSS so only #c1 is displayed.
It does work completely fine, but if i try to validate it it shows me an error message at row 2 and 3.
Ok thanks everyone for your help, there wasn't really an issue, I'm just new to JS and didn't know something.
I used a validator, that didn't use an engine, that supports let variables.

How to generate javascript code with javascript if posible

Im quite new at javascript so dont expect me to know much else than whats written :)
So i have a javascript file with a lot of javascript codes that almost looks the same except a number is changing with each element.
Most of my code are inside a function just not written since it's a cut out.
The relevant part of my code looks something like:
//Upgrade 1
if (CREDITS >= UpgradePrice1 && Upgrade1 === 0){
document.getElementById("Upgrade1").style.display = "block";}
else{document.getElementById("Upgrade1").style.display = "none";}
//Upgrade 2
if (CREDITS >= UpgradePrice2 && Upgrade2 === 0){
document.getElementById("Upgrade2").style.display = "block";}
else{document.getElementById("Upgrade2").style.display = "none";}
//Upgrade 3
if (CREDITS >= UpgradePrice3 && Upgrade3 === 0){
document.getElementById("Upgrade3").style.display = "block";}
else{document.getElementById("Upgrade3").style.display = "none";
And so on...
The values are assigned in a file named StandardValues.js:
var UpgradeName1 = "Craftmanship Lvl 1";
var UpgradePrice1 = 100;
var UpgradeContent1 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade1 = 0;
var UpgradeName2 = "Craftmanship Lvl 2";
var UpgradePrice2 = 200;
var UpgradeContent2 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade2 = 0;
And so on...
If it were a html code i tried to generate i would use a php while function and make it echo the same code with the changed number a specefic amount of times.
But since this is inside a javascript file i really dont think thats an option?
The javascript code from before is in a .js file.
I think a potential fix could be:
Inside a .php file:
<?php
$Upgrades = 10;
$CurrentUpgrade = 1;
while ($Upgrades >= $CurrentUpgrade){
echo "
<script>
function Upgrade1(){
//Upgrade ".$CurrentUpgrade."
if (CREDITS >= UpgradePrice".$CurrentUpgrade." && Upgrade".$CurrentUpgrade." === 0){
document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'block';}
else{document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'none';}
}
</script>
";
$CurrentUpgrade ++;
}
?>
*Sry for any typo in this part, made it quite quick.
But i would quite like to keep the javascript code inside my .js file instead of having it in my .php file.
So to sum it up i would like to (If possible):
Keep all code inside the .js file
Generate javascript code with javascript code
Repeat the same javascript element with only a number changing with each element
Try to shorten the amount of code by doing this.
Still be able to use any of the assigned variables alone somewhere like in a buy function.
I hope i gave all relevant information :)
Thanks in advance.
You can create a method (in index you are passing the number in the end of your variables):
function myFunction(newUpgradePrice, newUpgrade, index) {
if (CREDITS >= newUpgradePrice && newUpgrade === 0){
document.getElementById("Upgrade" + index).style.display = "block";}
else{document.getElementById("Upgrade" + index).style.display = "none";
}
Is This what you are looking for? Anything needing to be changed to meet your needs?

Simple Javascript loop for checking total size of multiple file

How can I implement this code into a loop for 20 files? They will have id="myFile1", "myFile2" etc.
<script type="text/javascript">
var myFile = document.getElementById('myFile');
myFile.addEventListener('change', function() {
alert(this.files[0].size);
});
</script>
My first idea was to do 20 scripts, but I don' really think that it would be good solution, I really prefer clean code.
I tried this... but doesn't work for some reason - the second file reports "NaN" instead of file size in bytes.
<script type="text/javascript">
var myFile = document.getElementById('myFile');
myFile.addEventListener('change', function() {
var totalSize = this.files[0].size;
alert(totalSize);
});
</script>
<script type="text/javascript">
var myFile1 = document.getElementById('myFile1');
myFile1.addEventListener('change', function() {
var totalSize = totalSize + this.files[0].size;
alert(totalSize);
});
</script>
I would also like to implement an IF conditional that would alert only if the totalSize were bigger than 7 MB, that means that I need the totalSize/(1024*1024) - easy to do, but not the loop .
Could you please help me building a working loop that would count the totalSize of all the files? myFile is an ID of input type="file" element.
Try and use following logic:
<script type="text/javascript">
var totalSize=0;
function checkSize() {
totalSize = totalSize + this.files[0].size;
alert(totalSize); //write logic to check size validation etc. here
}
for(var i=1;i<=20;i++)
{
var myFile = document.getElementById('myFile'+i);
myFile.addEventListener('change',checkSize);
}
</script>
I don't know if I understood correctly what you need, but this could be your case: http://jsbin.com/ozadak/2/edit
CODE
var totArray = [];
for (var x = 1; x <= 5; x++) {
var currFile = document.getElementById("myFile"+x);
currFile.addEventListener('change', function(x){
totArray[this.id] = parseInt(document.getElementById(this.id).value); //here goes file.size
var currTot = 0;
for(var key in totArray){
currTot += totArray[key];
}
if(currTot > 10)
alert("file sizes > 10 MB");
});
}
for simplicity I used some text input, to show how the loop works adding each input the same event. To test it, input an integer representing how many MB does your file weight, it should work.
Hope it helps, regards

javascript match only certain letters in array

I'm using the below in a javascript Q & A chatbot. To answer for example "what is AG in the periodic table? Answer is Silver.
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
document.result.result.value = "Hmmmm, I don't know. Try Google!";
for (i = 0; i < Periodic_Tables.length; i++) {
Periodic_Table = Periodic_Tables[i].split('=');
if (input.indexOf(Periodic_Table[0]) != -1) {
document.result.result.value = Periodic_Table[1];
}
}
return true;
}
Then I have in another file the array laid out like this:
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitro­gen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver"
);
My problem is because the table symbols are only 1 or 2 letters it's matching a lot of wrong things. How can I set this up where "only" b matches boron, be matches beryllium. etc I've looked a word boundaries but can seem to figure out how to use them here.
Instead of this code block which is checking if input contains a symbol:
if (input.indexOf(Periodic_Table[0]) != -1) {
document.result.result.value = Periodic_Table[1];
}
You should check for equality like this:
Periodic_Tables=new Array("h=Hydrogen",
"he=Helium", "li=Lithium", "be=Beryllium", "b=Boron", "c=Carbon", "o=Oxygen",
"f=Fluorine", "ne=Neon", "na=Sodium", "mg=Magnesium", "ag=Silver");
function Parse(input) {
input=input.toLowerCase();
input=input.replace(/[!|?|,|.]/g,"");
if (input.search(/\bu\b/)!=-1) input=input.replace(/\bu\b/,"you");
if (input.search(/\br\b/)!=-1) input=input.replace(/\br\b/,"are");
if (input.search(/\bk\b/)!=-1) input=input.replace(/\bk\b/,"ok");
if (input.search(/\by\b/)!=-1) input=input.replace(/\by\b/,"why");
var words=input.split(" ");
var result = "Hmmmm, I don't know. Try Google!";
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
for (var w=0; w<words.length; w++) {
for (i=0; i<Periodic_Tables.length; i++) {
Periodic_Table = Periodic_Tables[i].split('=');
if (words[w] == Periodic_Table[0]) {
result = Periodic_Table[1];
return result;
}
}
}
}
return result;
}
alert(Parse("what is h in periodic table"));
DEMO: http://jsfiddle.net/MnyFP/1/
First i'd use 2d array to store your periodic tables, so that you don't have to string split every time you want to use it.
Instead of
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitro­gen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver",
);
Use
Periodic_Tables = [
["h", "Hydrogen"],
["he", "Helium"],
...
]
Assuming that the question is well formatted, that the symbol "AG" has a space in front and after it. I think you could simple test the input against " AG ", or " ag ", if you make it case insensitive. Including the spaces in the test string will for it to find matches that is a word in it self, instead of part of another word.
Pretty use regex has similar abilities, but i am not sure how to do it with regex..
assuming that the question in the chat box ends with the name of the element, u can split the string at the punctuations.(lets say user enters, what is,ag)
function abc(str)
{
String[] parts = str.split("\\W+");
var len=parts.length();
String sub=parts[len-1];
var re=new RegExp("^"+sub+"$","i");
and then use a loop and check the condition
if(re.test(arr[i])){
document.write(arr[i]);
break;
}
}
I would use an array of objects:
Periodic_Tables = [
{Symbol: "h", Element: "Hydrogen"},
{Symbol: "he", Element: "Helium"}
...
]
Then your loop looks like this:
for (i = 0; i < Periodic_Table.length; i++) {
if (input.indexOf(Periodic_Table[i].Symbol) !== -1) {
document.result.result.value = Periodic_Table[i].Element;
}
}
This prevents having to use a regex or a 2d array, and is a little more readable.
I can't seem to get anything to work within the Q and A bot. So I put up a demo here:
http://www.frontiernet.net/~wcowart/aademo.html
Or here is the code: I tried many of the various answers presented. Maybe I'm not implementing them right.
<HTML>
<HEAD>
<TITLE>ChatterBot Page</TITLE>
<script language="JavaScript">
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitro­gen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver"
);
var message = new Array();
var randomnum;
var flagrandom;
function Parse() {
var input = new String(document.chat.input.value);
document.chat.input.value="";
input=input.toLowerCase();
word=input.split(" ");
num_of_words=word.length;
input=input.replace(/[!|?|,|.]/g,"");
word=input.split(" ");
if (input.search(/\bu\b/)!=-1) input=input.replace(/\bu\b/,"you");
if (input.search(/\br\b/)!=-1) input=input.replace(/\br\b/,"are");
if (input.search(/\bk\b/)!=-1) input=input.replace(/\bk\b/,"ok");
if (input.search(/\by\b/)!=-1) input=input.replace(/\by\b/,"why");
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
document.result.result.value = "Hmmmm, I don't know. Try Google!";
for (var i = 0, len = Periodic_Tables.length; i < len; i++) {
if (Periodic_Tables[i].match('^'+input+'=')) {
document.result.result.value = Periodic_Tables[i].split('=')[1] }
}
return true;}
if (!flagrandom) {
randomnum = [Math.floor(Math.random()*3)]
flagrandom=true;}
message[0] = "Sorry, you stumped me on that one.";
message[1] = "Sorry, a search of my data base comes up empty.";
message[2] = "Not sure";
document.result.result.value = message[randomnum];
randomnum++
if (randomnum>2){randomnum=0}
return true;}
</script>
</head>
<BODY BACKGROUND="FFFFFF" TEXT="#0000cc" LINK="#FFCOOO" ALINK="#FFCC99"
VLINK="#FFC000" marginwidth="0" leftmargin="0" topmargin="0" rightmargin="0">
<Center>
<font size="+3">
ChatterBot
</font>
<br>
<img src="botpix.jpg" border="0" WIDTH="200" HEIGHT="200">
<br>
<form name="result">
<textarea rows=5 cols=40 input type="text" name="result">
</textarea><br>
</form>
</center>
<form name="chat" onSubmit="Parse();return false">
<b>Type here:</b>
<input type="text" name="input" size="100">
</form>
</body>
</html>

Categories

Resources