Loading and removing images with DOM, Javascript - 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.

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">

Adding mouseover event to a javascript created DIV

Im currently getting data from Google places and am dynamically creating the div to display the results. I am trying to add a mouseover event to each div yet am having no luck implementing it. Ive check the html source and it seems to not add the event for any of the created DIV's.
JS:
for (var i = 0; i < relatedProperties.length; i++) {
var div = document.createElement("div");
div.innerHTML = relatedProperties[i].formatted_address;
div.className = "item_holder";
div.onmouseover = PanToMarker(relatedProperties[i].formatted_address);
document.getElementById('relatedpropertyDIV').appendChild(div);
}
function PanToMarker(address) {
//Grabs the address and pans to it on the map.
}
I would imagine you need to wrap your onmouseover function like this:
div.onmouseover = function() {
PanToMarker(relatedProperties[i].formatted_address);
};
This is because when you click on the element, the onmouseover function gets called with no arguments. When you specify arguments to PanToMarker like in your question, instead of assigning the function as may be intuitive, instead it executes the function then and there, and then assigns the function's output. Wrapping the function like this assures that the function doesn't get called instead while you're trying to assign it.
When you add the onmouseover event handler in this manner, you will not see it in the dom.
I would recommend that you store the index as a data property in the DOM. Then you will be able to access it from the mouseover method ...
for (var i = 0; i < relatedProperties.length; i++) {
var div = document.createElement("div");
div.innerHTML = relatedProperties[i].formatted_address;
div.setAttribute('data-index', i);
div.className = "item_holder";
div.onmouseover = PanToMarker;
document.getElementById('relatedpropertyDIV').appendChild(div);
}
function PanToMarker() {
var selectedIndex = this.getAttribute('data-index');
map.panTo(relatedProperties[selectedIndex].geometry.location);
}
There may be performance implications since you will be appending i elements to the DOM, each of which may cause a re-draw. It might be better to create all the elements first, then append once.
var section = document.createElement('section');
for (var i = 0, length = relatedProperties.length; i < length; i++) {
var div = document.createElement("div");
div.innerHTML = relatedProperties[i].formatted_address;
div.setAttribute('data-index', i);
div.className = "item_holder";
div.onmouseover = PanToMarker;
section.appendChild(div);
}
document.getElementById('relatedpropertyDIV').appendChild(section);
function PanToMarker() {
var selectedIndex = this.getAttribute('data-index');
map.panTo(relatedProperties[selectedIndex].geometry.location);
}

Why this javascript does not work?

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);

Javascript function to fire after images have finished loading (no jQuery)

I have the following code (the relevant parts):
window.addEventListener("load", loadImages, false);
var imgl = new Array();
function loadImages() {
var img = [
"img1",
"img2",
"img3",
"etc"
];
imgl[img.length-1].onload = function () {
alert();
initialise();
}
for (i = 0; i < img.length; i++) {
imgl[img[i]] = new Image();
imgl[img[i]].src = "img/"+img[i]+".png";
}
}
function initialise() {
//...
}
and I want to fire the initialise() function after all the images have finished loading, but nothing I tried worked. (Btw the alert() in the example is for testing, and I'm not getting it.) Why is this wrong? Other methods of doing this are also appreciated.
also I don't want to use jQuery, only if absolutely unavoidable.
Thanks in advance.
EDIT:
The following doesn't work either, although making more sense:
for (i = 0; i < img.length; i++) {
imgl[img[i]] = new Image();
}
imgl[imgl.length-1].onload = function () {
initialise();
}
for (i = 0; i < img.length; i++) {
imgl[img[i]].src = "img/"+img[i]+".png";
}
imgl[img.length-1] doesn't exist, therefore cannot have an "onload" property.
You initialize img1 at the beginning, but never populate it.
In other words:
img.length-1 = 3
img1[3] doesn't exist.
I'm getting the following error message:
Uncaught TypeError: Cannot set property 'onload' of undefined

Categories