Why this javascript does not work? - javascript

I am having some trouble with this code, I tested it online but it doesn't seem to work. This is all of my coding:
My HTML:
<img src="kruisje.jpg" id="image1">
And the script that SHOULD make it a slideshow but doesn't:
var img = document.getElementById("image1").src;
function changeimage(){
wait(10)
for(var i = 0; i < images.length; i++){
return img
}
}
var images = ["","","","","",""]
And I know the links in the array aren't filled in but I have the links for it ready. They are just pictures so you can fill in any url you want if you are testing it.
Can somebody say me what i am doing wrong on this code?

Depending on when you run it, document.getElementById("image1") may return an element or null. If it returns null the script will error when you try to access the src property and abort.
You never call the changeimage function
There is no wait function in JavaScript and you don't appear to have defined one.
You return img, so you exit the function on the first time you go around the loop
If you wanted to assign a new URL to img then you would just be assigning the URL to the variable. img will be a variable containing a string. It won't reference the src property.
If you want to do this, you need to completely change your approach.
// Get a reference to the element (make sure you run this *after* the image has been added to the DOM)
var img = document.getElementById("image1");
// Track where you are in the array
var imagesIndex = 0;
var images = ["","","","","",""]
function changeImage(){
// Assign the new URL to the src property of the image
img.src = images[imagesIndex];
// Increment the index here
imageIndex++;
// Check if it has gone off the end and reset it if it has
if (imageIndex >= images.length) {
imageIndex = 0;
}
}
// Call the function on your time period
setInterval(changeImage, 10000);

var img = document.getElementById("image1").src;
function changeimage(){
wait(10) // ERROR FUNCTION
setTimeout(function(){alert("Hello")},3000);
for(var i = 0; i < images.length; i++){
return img
}
}
var images = ["","","","","",""]
you need use setTimeout(function(){alert("Hello")},3000);

Related

How to preload images for a game in the simplest way possible? (pure js, no library)

I want to have game.js which will only start execution when all the necessary images have been preloaded. The best way I can think of is something like:
var numberOfImagesToPreload = 2;
var imgsLoadedSoFar = 0;
var sources = ['player.png', 'terrain.png'];
for(let i = 0; i < sources.length; i++) {
var anImage = new Image();
anImage.src = sources[i];
anImage.onload = function() {
imgsLoadedSoFar++;
}
};
console.log(imgsLoadedSoFar);
if(imgsLoadedSoFar === numberOfImagesToPreload) {
console.log("Done, now start executing game.js");
};
Clearly this doesn't work because of async problems and I want to have preloader.js that will load the images first and then I want to launch game.js in which each image(game object) will have update and draw methods. If you think this shouldn't be done that way please suggest how. Thanks a lot.
EDIT
I am making some progress on this. Once the preloader.js loads all the resources I call a function in game.js function(image) but still not what I am looking for, which is basically once game.js starts loaded ALL the images should be loaded already.
Move the if inside your loop?
for(let i = 0; i < sources.length; i++) {
var anImage = new Image();
anImage.src = sources[i];
anImage.onload = function() {
imgsLoadedSoFar++;
if(imgsLoadedSoFar === numberOfImagesToPreload) {
console.log("Done, now start executing game.js");
};
}
};
Add a global boolean variable to switch to true only after preloading, wrap the functions on game.js in an if statement, once the boolean becomes true make call the function in game.js

Carousel of Images Will Not Advance (HTML/JavaScript)

I am attempting to have the carousel start immediately upon visiting the page and cycle through a series of images every 2.5 seconds, however it will not advance past the first image. I've looked around here and w3schools but haven't been able to locate where my issue is. Any help would be greatly appreciated!
JavaScript is as follows:
window.onload slideShow();
var i=0;
function slideShow() {
window.setInterval("nextSlide()", 2500);
}
function nextSlide() {
var images["images/stockton0.jpg",
"images/stockton1.jpg"
"images/stockton2.jpg"
"images/stockton3.jpg"
"images/stockton4.jpg"
"images/stockton5.jpg"
"images/stockton6.jpg"
"images/stockton7.jpg"
"images/stockton8.jpg"
"images/stockton9.jpg"
"images/stockton10.jpg"]
var photo = document.getElementByClass("stocktonPics");
photo.src = images[i];
i++;
}
HTML code:
<img class="stocktonPics" src="images/stockton0.jpg" alt="slides">
A good tip is to check the console for errors.
There's nothing wrong with the flow of your code, besides some tips on making it more maintainable, readable, or semantically correct.
You simply forgot an = in window.onload = slideShow;
And document.getElementByClass doesn't exist. You need to use document.getElementsByClassName(...) to get an array of elements with that class, and finally get its first item with [0] like so:
var photo = document.getElementsByClassName("stocktonPics")[0];
Note that slideShow no longer has the () to call it, when window.onload is assigned to it. This is because you're assigning window.onload to the slideShow function, not the result of calling slideShow(), which in this case is undefined, as nothing is returned.
Your image array should be assigned in this way: var images = [ a, b, c ]
The other thing you should do is keep the array of images outside the scope of the function, so you can use it more easily and change it, rather than creating one (if you don't count optimizations) ever time the function is called. And lastly, window.setInterval( a, b ) can take either a string that will be eval()ed (or equivalent to it), which is what you did, or a function itself. In your case, what you want is simply the function: window.setInterval( nextSlide, 2500 ).
Here's the final full code:
var i=0;
var images=[
"images/stockton0.jpg",
"images/stockton1.jpg",
"images/stockton2.jpg",
"images/stockton3.jpg",
"images/stockton4.jpg",
"images/stockton5.jpg",
"images/stockton6.jpg",
"images/stockton7.jpg",
"images/stockton8.jpg",
"images/stockton9.jpg",
"images/stockton10.jpg" ];
function slideShow() {
window.setInterval( nextSlide, 2500);
}
function nextSlide() {
var photo = document.getElementsByClassName("stocktonPics")[0];
photo.src = images[i];
i++;
}
window.onload = slideShow;
getElementsByClass
method is will get a like array elements object,
so, you should use [0] to get the first element object and set src attr.
var pics = document.getElementsByClassName("stocktonPics")
It's a like array elements object
var firstPic = document.getElementsByClassName("stocktonPics")[0]
It's a element object
let i = 0;
const images = ["images/stockton0.jpg",
"images/stockton1.jpg",
"images/stockton2.jpg",
"images/stockton3.jpg",
"images/stockton4.jpg",
"images/stockton5.jpg",
"images/stockton6.jpg",
"images/stockton7.jpg",
"images/stockton8.jpg",
"images/stockton9.jpg",
"images/stockton10.jpg"];
const stockton = document.getElementsByClassName("example")[0];
const slideShow = () => {
window.setInterval(nextSlide, 2500);
}
const nextSlide = () => {
stockton.src = images[i];
if(i >= images.length - 1) {
i = 0;
} else {
i++;
}
console.log(i, stockton)
}
slideShow()
<img class="example">

javascript generate repeated images in meteor

Can anyone help I am trying to have an image that repeats according to how many portions there are. I am getting Uncaught TypeError: Cannot set property 'src' of undefined.
I am using meteor and react
genPrtnImg: function () {
var pNum = FoodItemsC.find(this.props.foodItem.portionNo);
for (i = 0; i < pNum; i++)
var img = document.createElement('img');
img.src = "http://downloadicons.net/sites/default/files/carrot-icon-14142.png";
return img;
},
the function is called in the render below:
render() {
return (
<tbody>
<tr>
<td rowSpan="3"><img className="itemSmlPic" src="http://bed56888308e93972c04-0dfc23b7b97881dee012a129d9518bae.r34.cf1.rackcdn.com/sites/default/files/veggie-heart.jpg"></img></td>
<td><h1>{this.props.foodItem.foodName}</h1></td>
<td rowSpan="3"><img className="itemSmlPic" src="http://thesocialmediamonthly.com/wp-content/uploads/2015/08/photo.png"></img></td>
</tr>
<tr>
<td>{this.props.foodItem.foodDesc}</td>
</tr>
<tr>
<td>{this.genPrtnImg()}</td>
</tr>
</tbody>
);
}
Thanks!
You are not enclosing your entire for loop inside curly brackets so your for loop is actually only iterating over this line var img = document.createElement('img');. Because of this and the fact that your var is declared inside the for loop i.e. doesn't exist outwith that one line of code when you hit the next line and do img.src = you get your error because img doesn't actually exist here. Fix is to wrap in brackets
for (i = 0; i < pNum; i++) {
var img = document.createElement('img');
img.src = "http://downloadicons.net/sites/default/files/carrot-icon-14142.png";
}
B) This still wont work because when you return img you are also returning outside the scope of the for loop hence the img does not exist. You could move it inside the for loop but this would mean it would only ever execute the loop once and as soon as it hits the return line it will return a singular img value
EDIT:
A fix for this would possibly be to push these values to an array and return that (wrapped in an element so react doesn't have a wipe out):
genPrtnImg: function () {
var pNum = FoodItemsC.find(this.props.foodItem.portionNo);
var i=0;
var x = [];
for (i = 0; i < pNum; i++){
x.push(<img src='http://downloadicons.net/sites/default/files/carrot-icon-14142.png' />);
}
return <div>{x}</div>;
}

Javascript: How do I get the height of unloaded images in a loop?

I am loading a json file and parsing it into an array in Javascript. One of the elements is the path to an image. I am not ready to load the images yet but I need to get the image's height. I know how to do that with code like the following (found on other stackoverflow pages)
function getimageheight(img) {
var tmpImg = new Image();
tmpImg.onload = function() {
var ht = this.height;
return ht+0;
}
tmpImg.src = img;
}
If I try to call this function in a loop, it returns undefined because the onload for the images is running slower than the loop. My actual code is this:
var j = 0;
$.each(cat.placemarks, function(index, mark) {
markers[cat.name][j] = [];
markers[cat.name][j].name = mark.name;
markers[cat.name][j].title = mark.title;
markers[cat.name][j].markerURL = mark.markerURL;
markers[cat.name][j].imageURL = mark.imageURL;
markers[cat.name][j].imageHEIGHT = getimageheight(projpath+mark.imageURL);
j++;
});
If I call the function once, it works. But calling it in a loop does not. How can I fix this?
If you store reference to data object in Img object used to load it, you can set the value of its properties after the loading is done. Hope that makes sense... Your data will not be ready to use before loading is complete tho. Heres the code
var total=cat.placemarks.length;//if an array, otherwise use another each cycle to get object count
var loaded=0;
$each(cat.placemarks, function(index, mark) {
markers[cat.name][j] = [];
var tmpImg = new Image();
tmpImg.refToObjWithNameOfYourChoice=markers[cat.name][j];
tmpImg.onload = function() {
this.refToObjWithNameOfYourChoice.imageHEIGHT=this.heigh;
loaded++;
if(loaded==total){
//markers data is ready to use - add function callback herer or sumthin'
}
}
tmpImg.src=projpath+mark.imageURL;
markers[cat.name][j].name = mark.name;
markers[cat.name][j].title = mark.title;
markers[cat.name][j].markerURL = mark.markerURL;
markers[cat.name][j].imageURL = mark.imageURL;
j++;
});
markers[cat.name][j].imageHEIGHT is undefined because getImageHeight() isn't returning anything. And naturally, the image load will occur much more slowly than your each() loop, so it won't do you any good to have getImageHeight() return something. You'll have to set up your load() callback to determine which image has been loaded and update the height of the corresponding markers element.

Loading and removing images with DOM, Javascript

I'm new to DOM and I'm having trouble removing multiple images that I loaded
this loads 7 images (1.jpg, 2.jpg, etc..)
function loadImages() {
for (var i = 1; i < 8; i++ ) {
var img = document.createElement("img");
img.src = "images/"+i+".jpg";
var idName = "img"+i+"";
document.getElementById(idName).appendChild(img);
}
}
this should remove all of them, but doesn't.. I think it breaks at the removeChild line.
function removeImages() {
for (var i = 1; i < 8; i++ ) {
var idName = "img"+i+"";
var d = document.getElementById(idName);
d.removeChild(document.getElementById(img));
}
}
I think I'm doing something fundamentally wrong, because I don't fully understand how this works...
In the removeImages function the variable img is not initialized. And even if it was you don't set the id for any of the images in the loadImages function. You could modify your code like this:
function loadImages() {
for (var i = 1; i < 8; i++ ) {
var img = document.createElement("img");
img.src = "images/"+i+".jpg";
img.id = i;
var idName = "img"+i+"";
document.getElementById(idName).appendChild(img);
}
}
function removeImages() {
for (var i = 1; i < 8; i++ ) {
var d = document.getElementById(i);
d.parentNode.removeChild(d);
}
}
Your code example implies that you're trying to remove a child element of the image and not the image itself. Also, you're using the wrong variable to reference the image. Maybe it works when you replace this line:
d.removeChild(document.getElementById(img));
With this:
d.parent.removeChild(document.getElementById(idName));
Also, if you're not that familiar with the DOM tree, you might want to take a look at jQuery, which is more browser-independent than regular DOM instructions.
If you are doing DOM manipulation, I would recommend that you use jQuery (or at least try it out).
It will make your life more pleasant, you will be a happier person and it will prevent you from committing harakiri.

Categories