Array syntax error newbie - javascript

I am lost in this error. I am trying to write a function and write a array in that function. in an external js file. This is going to be a random image loading function but i keep getting an error with the array and can't figure out why.
function randImg(){
var imgs = new Array();
img[0]="banner1.png";
img[1]="banner2.png";
img[2]="banner3.png";
var maxium = img.length;
}
I am getting the error on the var imgs line. any ideas?
Here is my new code calling the variable "img" was throwing me off it loads ok but it only prints out the text in the variable and not the actually file!? so at run it say "banner1.png" or "banner3.png"? any thoughts
function randImg(){
var banner = new Array();
banner[0] = "banner1.png";
banner[1] = "banner2.png";
banner[2] = "banner3.png";
var maxImg = banner.length;
var randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}

A better way to define the array with its elements:
var img = [
"banner1.png",
"banner2.png",
"banner3.png",
"banner4.png"
]
And this is the function you might need:
function randImg(){
var img = [
"banner1.png",
"banner2.png",
"banner3.png",
"banner4.png"
]
var maxImg = img.length;
var randNum = Math.floor(Math.random()*maxImg)
return img[randNum]
}

Your variable names should be consistent. You created the new Array imgs (local variable), yet you added to img (defaulted to global variable, since you didn't declare it a local variable).
Also, note that in Javascript it doesn't make too much sense to add a var statement that is not the first line of a function. This is because of hoisting. Essentially, Javascript will take your var and move it to the first line, setting the variable to undefine. This may or may not affect how your program works vs how you think it should work, so it's best to add all your vars at the top of your functions. Javascript has function scope, not block scope.
(also note that maximum is a more meaningful variable name than maxium)
// This adds to the newly created array:
function randImg(){
var img = new Array(), // Note: img NOT imgs
maximum; // Even if a var is below this line, Javascript hoists it here
img[0] = "banner1.png";
img[1] = "banner2.png";
img[2] = "banner3.png";
maximum = img.length;
}
and you can use .push() if you're just adding to the end of an array (like you're doing)
function randImg(){
var img = new Array(), // Note: img NOT imgs
maximum;
img.push("banner1.png");
img.push("banner2.png");
img.push("banner3.png");
maximum = img.length;
}
or
function randImg(){
var img = new Array(), // Note: img NOT imgs
maximum;
img.push("banner1.png").push("banner2.png").push("banner3.png)";
maximum = img.length;
}
or better yet, just use [] to initialize an empty array or [a,b,c,...] to initialize an array with elements. Also, why use var twice?
function randImg(){
var img = ["banner1.png","banner2.png","banner3.png"], // note comma
maximum = img.length;
}
Finally, to live up to the name of the function
var randImg = function() {
var img = ["banner1.png","banner2.png","banner3.png"];
return img[Math.floor(Math.random()*img.length)];
}
... and here's a working example of randImg()

Related

Create variable to JavaScript array from another function?

I have a function that create and store an array for all the p elements:
function dummyArray(){
var $dummy= $('p');
var dummy= [];
i = 0;
$dummy.each(function()
{
dummy[i++] =$(this).html();
});
return dummy;
}
Now, in order to reuse the array in another function, I can use dummyArray() and dummyArray()[0] to access the individual data.
function initAll(){
//dummyArray();
//dummyArray()[0];
}
However I want to store it inside a variable like below but it gives me error.
function initAll(){
var allArray = dummyArray();//error
}
Is there a way to store it inside a variable or is there a better way of doing this?
After cleaning up my code I noticed that using var allArray = dummyArray(); does work, the error was generated from something else. cheers~
Edited:
The error I found out was the function name cannot be the same as the new variable name declared even though the () aren't there.
var dummyArray = dummyArray();//error
var allArray = dummyArray();//works

javascript: save a variable's value between calls?

I have some code that looks like this:
createEntity = function (imageSource, baseX, baseY) {
tmpIndex = images.length;
images[tmpIndex] = new Image();
entities[tmpIndex] = new Entity;
images[tmpIndex].onload = function () {
entities[tmpIndex].ready = true;
// How do I get the line above to use the value of tmpIndex
// that existed when it was created?
// That is to say, I want the images[1].onload function to
// change entities[1].ready, not entities[4].ready
// (assuming I created 5 objects sequentially
// before any images finished loading)
}
images[tmpIndex].src = imageSource;
entities[tmpIndex].x = baseX;
entities[tmpIndex].y = baseY;
}
createEntity("images/background.png", 0, 0);
createEntity("images/pawn1.png",0,0);
createEntity("images/pawn2.png",30,30);
createEntity("images/pawn3.png",60,60);
createEntity("images/pawn4.png",90,90);
The problem is that when I load all 5 images sequentially, as the above code shows, my onload function triggers with the current value of tmpIndex, not the one that existed when the function was created. Is there a simple way to make it so that the entities[somenumber].ready is toggled appropriately?
You need to declare tmpIndex as a local variable. To do this change
tmpIndex = images.length;
to
var tmpIndex = images.length;
Why does tmpIndex have to be visible outside of createEntity function? If it doesn't, just declare it inside your function, like this: var tmpIndex = images.length;
Your onload callback will be able to read its value even after the createEntity function has finished executing because will keep a reference to the scope where it was created.
Every execution scope is different, so every time you call createEntity you create different scope and a different onload callback function which stores a reference to that execution scope, and therefore is able to consume variables defined there.
Exactly. Here's a working JSfiddle example catching onerror instead on onload : http://jsfiddle.net/bdn2775k/1/
Here's the revelant part :
//Don't forget to declare a local variable !
var tmpIndex = images.length;

javascript function to save data in global variables

I have problems to make this function (addMe) to save the data from img and span from div childBox in two global arrays?
I think something is wrong in the function but can't see what.
This is my code.
Global var: //before function init
var imgSrclist = [];
var imgSpanlist = [];
Function:
function addMe(obj) {
var el = document.getElementById(obj.getAttribute('data-img'));
var parent = el.parentNode.getElementsByClassName('childBox')[0],
imgSRC = parent.getElementsByName('img')[0].src,
spanTXT = parent.getElementsByTagName('span')[0].innerHTML;
if (obj.checked) {
imgSpanlist[el.id].imgSrc.push(imgSRC);
imgSrclist[el.id].imgSpan.push(spanTXT);
} else {
var imgIx = imgSrclist[el.id].imgSrc.indexOf(imgSRC),
spanIx = imgSpanlist[el.id].imgSpan.indexOf(spanTXT);
imgSrclist[el.id].imgSrc.splice(imgIx);
imgSpanlist[el.id].imgSpan.splice(spanIx);
}
}
The data should be saved on global variabels because it will be used later in a new window when you push a button. The script code for the new windows starts with this:
var imgSrclist = window.opener.imgSrclist;
var imgSpanlist = window.opener.imgSpanlist;
EDIT: The code is now updated, so the arrays is declared. But the problem is that the imgsrc and span text dosen´t comes to the new window. are they saved in the array at all?
Two things I want to mention is;
var imgSrclist;
var imgSpanlist;
should declare as an array and
function init() {
imgSrc=[]; //Empty array
imgSpan=[]; //Empty array
}
why they are declare as an array as you are not using these as an array.
I have updated two above changes, here is your code.

Uncaught TypeError cannot set property 'src' of null

So on my new website in google chrome, I am trying to make the images switch every 5 seconds using a setInterval function. This seems to work, however I have the problem cannot set property src of null.
var images = new Array();
images[0] = "/images/grilled-chicken-large.png";
images[1] = "/images/sizzly-steak.png";
var img = document.getElementById("img");
function changeImage() {
for (var i = 0; i < 3; i++) {
img.src = images[i];
if (i == 2){i = i - 2;};
}
}
window.onload=setInterval("changeImage()", 5000);
I know the problem is that I am trying to get the element with an id of img before the page is done loading, but I've already got a window.onload, so i don't know what to do. Also, if i make an init() function containing the setInterval and the img variable, the page freezes.
Any ideas?
The problem is that you access element 2 of an array with only two elements (0 and 1).
But there is also a logical error in your script: Where do you store the index of the currently visible image? You need a global variable which holds that index.
var currentIndex = 0;
function changeImage() {
// Switch currentIndex in a loop
currentIndex++;
if (currentIndex >= images.length)
currentIndex = 0;
var img = document.getElementById("img");
img.src = images[currentIndex];
}
document.onload = function() {
setInterval(changeImage, 5000);
}
I've moved the img variable into the function so that it is assigned after five seconds when the document has loaded.
Just to clear things up: JavaScript is an event-based programming language. That means that the slideshow-change code is executed every time the interval fires, does some work (switch to the next slide) and then is done, so that the browser can render the page. If you iterate through the slides in a loop, there is no way for the browser to show the new slide because the script is still executing between the slides. The solution is what I've posted: Define a global variable that replaces the loop variable, and increment it every time the next slide is to be shown.
Here:
window.onload = function () {
var images = [
'http://placekitten.com/100/200',
'http://placekitten.com/200/100',
];
var img = document.getElementById( 'img' );
setInterval(function () {
img.src = img.src === images[0] ? images[1] : images[0];
}, 1000 );
};
Live demo: http://jsfiddle.net/wkqpr/
If you have more than two images, you can do this:
window.onload = function () {
var images = [
'http://placekitten.com/100/200',
'http://placekitten.com/200/100',
'http://placekitten.com/200/150',
'http://placekitten.com/150/300'
];
images.current = 0;
var img = document.getElementById( 'img' );
setInterval(function () {
img.src = images[ images.current++ ];
if ( images.current === images.length ) images.current = 0;
}, 1000 );
};
Live demo: http://jsfiddle.net/wkqpr/1/
Your for loop looks odd. Try that loop:
function changeImage(){
if(!img.attributes["index"]){img.attributes["index"]=0;return;};
img.attributes["index"]++;
img.src=images[img.attributes["index"]];
}
window.onload=function(){
window.img=document.getElementById("img");
setInterval("changeImage()",5000)
}
Should work.
You'll notice that I store the image index in an attribute of the image, as opposed to
a global variable. I think the global is slightly faster, but storing it in the image
means you can easily expand this to multiple images if needed.
Also, the problem with your browser freezing was that the following code:
for(var i=0;i<3;i++){
//Some more stuff
if(i==2){i-=2};
}
This loop is infinite, because whenever i reaches 2, i==2 becomes true, which means that iteration will reset i to 0 and start it all over again. The only way to prevent that would be a break; somewhere, which I don't see anywhere.
Tip: It is generally a bad idea to tamper with the index variable in for loops.
function changeImage()
{
for (var i = 0; i < 2; i++)
{
img.src = images[i];
}
}
window.onload=function()
{
setInterval(changeImage,5000);
}
Your last line in the for loop is completely useless and just complicate things,
Also, Your way of setting a window onload event is not standard!
EDIT: the src property is null because , obviously, your array size is only 2!!

Javascript document.getElementsByClassName returning undefined

I have a function which should be fairly straightforward and is supposed to be done after loading in order to reduce initial load time.
Basically I am using this code to get all of the elements with class "prefImg" and do some stuff with them. But when debugging in firebug, it says that the var divsList is undefined.
function populatePrefsList()
{
var divsList = new Array();
divsList = document.getElementsByClassName("prefImg");
var x = divsList.length;
var i = 0;
for(i=0; i<divsList.length; i++) {
var imgs = divsList[i].getElementsByTagName("img");
var imgSRC = imgs[0].src;
var alt = imgs[0].alt;
var descs = divsList[i].getElementsByTagName("h4");
var desc = descs[0].innerHTML;
//var thisPref = new preference(imgSRC, alt, desc);
//prefsList[i] = thisPref;
}
}
Obviously I have the breakpoint on var x = divsList.length...
I cannot understand this, I initially had the script in the Head of the page, but figuring it may have not loaded the divs yet, have moved it to the bottom of the Body. This did not solve it.
I have had var divsList = document.getElementsByClassName("prefImg");
If anyone could tell me where I have gone wrong then I would be grateful. There are about 50 divs with the className prefImg.
Cheers
You can use querySelectorAll instead of getElementsByClassName:
change divsList = document.getElementsByClassName("prefImg");
to this divsList = document.querySelectorAll(".prefImg");
DEMO - http://jsfiddle.net/ya3gU/
BTW, you do not need to declare the array divsList before you set it. Just do:
var divsList = document.querySelectorAll(".prefImg");
do not write this code in the head..
because this means the body did not load yet.
do it in the end of your body tag or use-
window.addEventListener("load", function()
{
// code here
});
you can use an eventhandler to the load event of the window object, to run the script only when the window has finished load
function populatePrefsList()
{
var divsList = new Array();
divsList = document.getElementsByClassName("prefImg");
var x = divsList.length;
var i = 0;
for(i=0; i<divsList.length; i++) {
var imgs = divsList[i].getElementsByTagName("img");
var imgSRC = imgs[0].src;
var alt = imgs[0].alt;
var descs = divsList[i].getElementsByTagName("h4");
var desc = descs[0].innerHTML;
//var thisPref = new preference(imgSRC, alt, desc);
//prefsList[i] = thisPref;
}
}
window.onload = function(){
populatePrefsList();
}
Older browsers (like IE6, IE7, IE8) doesn´t support getElementsByClassName and so they returns undefined.
In newer browsers the return value is never undefined. It is
mostly a HTMLCollection (but after W3C spec it should be a NodeList).
https://developer.mozilla.org/en/DOM/document.getElementsByClassName
But I think in your case the real problem is a bug in Firebug:
http://code.google.com/p/fbug/issues/detail?id=5336
It is fixed and a patch is committed and will be part of Firebug 1.10a6
Because it returns a HTMLCollection, so you should add a [number] at the end of the line:
divsList = document.getElementsByClassName("prefImg")[0];
Also it is a good idea to load this function after everything load completely by using:
window.load = function() {
populatePrefsList();
}
This is not supported by all browsers...any browser that does not support it, you would have to implement your own.
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName)
return node.getElementsByClassName(classname);
else {
// custom
}
}

Categories

Resources