The array won't work with the output of my pictures - javascript

I tried to show pictures with an array so I can change it per delay, kinda like a slideshow. The problem is, that only the first picture will load. when the counter of the array changes, the picture won't load.
The paths of the images are all correct
<!DOCTYPE html>`enter code here`
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test2</title>
<script>
var bilder = [];
var zeit = 3000;
var p = 0;
bilder[0] = "../Bilder/Bild1.jpg";
bilder[1] = "../Bilder/Bild2.jpg";
bilder[2] = "../Bilder/Bild3.jpg";
bilder[3] = "../Bilder/Bild4.jpg";
function BildAutoWeiter()
{
document.bild.src = bilder[p];
for( var i=0; i<= bilder.length; i++)
{
if(i <= bilder.length)
{
p++;
}
else
{
i = 0;
}
}
setTimeout("BildAutoWeiter()", zeit);
}
</script>
</head>
<body onload="BildAutoWeiter()">
<div>
<img name ="bild" width="100%" height="50%">
</div>
</body>
</html>

You need to use getElementsByName() to choose elements by their name=''. That returns an array of elements that use that name, so to choose a specific one, use an index [index] starting from 0. Do this instead:
document.getElementsByName('bild')[0].src = bilder[p];
That selects the first element that uses name='bild'
Also, the for statement is a bit useless. You could instead do:
function BildAutoWeiter()
{
document.bild.src = bilder[p];
p++;
setTimeout(BildAutoWeiter, zeit);
}
You don't need to put the function name in quotations and you can't have the parentheses while calling the function in setTimeout.

Related

using javascript in html to delete things when clicked

I have previously posted about this page Im trying to create and Im still running into errors. I am very new to this and getting confused. I need to use a for loop to loop over the images and assign an event listener to each one so that when they are clicked on they get deleted. Im getting confused with the difference variables and pulling the html into my javascript. I keep getting ".addEventListener is not a function" and so I keep changing things but getting lost.
<!DOCTYPE html>
<html>
<body>
<div id = 'img'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img"/>
</div>
<script text="javascript">
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++){
images[i].addEventListener("click", () => {
images[i].remove();
});
}
</script>
</body>
</html>
You are accessing array directly, which won't have the addEventListener. Try images[i].addEventListener
images.addEventListener should be images[i].addEventListener. You want to add the listener to the specific image from the array, not the array itself. Similar problem with images.remove().
First, you have same id for your container and both of your images - ID is supposed to be unique.
Second, as people already mentioned, you can not attach eventListener to array of objects.
Something like this shoud do:
let images = document.querySelectorAll("[id^='img']");
for (let i = 0; i < images.length; i++){
images.forEach(i=>{i.addEventListener("click", () => {
i.remove();
});
});
}
<div id = 'box'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img1"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img2"/>
</div>
you cannot attach an event handler to a list of images
so loop over images and for each of them
// for each image in images
image.onclick = function (e) {
e.target.parentNode.removeChild(e.target);
This will help you - https://jsfiddle.net/n5mk9Lzj/
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
images[i].remove();
});
}
You need to update your code, you are not using index inside loop.You cannot add any listener on directly to images array.
<!DOCTYPE html>
<html>
<body>
<div id = 'img'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img"/>
</div>
<script text="javascript">
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++){
images[i].addEventListener("click", () => {
images[i].remove();
});
}
</script>
</body>
</html>

Control if object is clicked or not in if statement

I'm building a small memory game. Where the user is presented by different objects that are displayed one at a time (which is done by an animation). The user can choose or not choose to click an object. The user is presented with a list indicating which objects should not be clicked, if the user clicks an object that should be clicked he gets one point. If the user decides to not click on a faulty object he should be rewarded one point as well. And the latter is my question, how can I control when the user doesn't click an object? My if statement right now only checks when the user actually clicks an object.
I'm aware that I need to move the verify function to my setTimout call for each object. But I'm not sure what to look for in the if statement?
function createShapes() {
var classes = [
"shape blue size200",
"shape size200 bluetriangle",
];
var id = [
"wrong",
"right",
];
var randomOrderArray = [];
for (i = 0; i < classes.length; i++) {
var randomElement = document.createElement("div");
randomElement.setAttribute("id", id[i]);
randomElement.setAttribute("class", classes[i]);
randomElement.classList.add();
randomOrderArray.push(randomElement);
}
// Calls shuffleArray
shuffleArray(randomOrderArray);
for (i = 0; i < randomOrderArray.length; i++) {
objectElement.appendChild(randomOrderArray[i]);
}
}
// Adds eventlisteners to shapes
var objects = document.querySelectorAll(".shape");
for (i = 0; i < objects.length; i++) {
objects[i].addEventListener("click", verifyShapes);
});
}
let counter = 0;
// Verifies clicked objects
function verifyShapes() {
if (this.id == "right") {
points++;
this.removeEventListener("click", verifyShapes);
counter++;
}
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>.....</title>
<body>
<div class="content" id="content"></div>
<div class="object" id="object"></div>
</body>
</html>

Javascript image swap sequence

As a task i am going to make traffic lights change in sequence when a button is pushed.I am going to do this by using a variable and adding one to it each time a image is shown therefore the computer knows what image to display next through the use of if and elses however i am not great at javascript and it will not run i have tried in many different environments for example in dreamweaver and notepad ++ but am getting no where here is what i have got :
<HTML>
<head>
<title>Untitled Document</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap(a)">GO</button>
</body>
<script>
var a = 0
function imageswap(a)
{
if (var a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
var a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.png';
var a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.png';
var a==0;
}
}
</script>
</html>
Thank you for reading and i would appreciate anyones help.
edit:
I have taken on feedback and amended my code but when testing it does not show the image i would like instead the little x .
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0
function imageswap()
{
if (a=0) {
document.getElementById('IMAGE').src='red_empty_empty.gif';
a = a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.gif';
a = a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.gif';
var a=0;
}
}
</script>
</html>
edit:
I have taken into account some recommendations and now when i click the button the first image is shown followed by the second on a second button press however it fails to display the third image and the first and second image dont always work first time.
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0;
function imageswap() {
if (a == 0) {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a += 1;
} else if (a == 1) {
document.getElementById('IMAGE').src = 'empty_amber_empty.gif';
a += 1;
} else {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a = 0;
}
}
</script>
in you first line var a = 0 you declare your counter (the var a part) and initialise it by assigning the value 0 (the a = 0 part), therefore there's no need to declare the variable again later, you just want to update it by assigning new values
so the statement if (var a==0) would be incorrect syntactically, because you can't check if a variable declaration is 0. you can of course check if the previously declared variable has a value of 0, which would be if (a==0)
same goes when you try to increment the counter value. var a + 1; is wrong, because you can't increment by 1 a declaration. you should instead assign to the existing counter, the value of itself plus 1, so a = a + 1;
finally, when you try to reset the counter, var a==0;, (beside the usual declaration error) remember that == is comparison and = is assignment. You shouldn't check if the counter is 0, you should assign the value 0 to the counter to reset it.
hope it helps
I Apply with in console.log(a).It will show the increment of a\
Apply the var a in globel It will increment on each time of you click
And increment Apply with a +=1 instead of a+1
var a = 0
console.log(a)
function imageswap(){
if (a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
a += 1;
console.log(a)
} else if (a==1){
document.getElementById('IMAGE').src='empty_amber_empty.png';
a += 1;
console.log(a)
} else {
document.getElementById('IMAGE').src='empty_empty_red.png';
a =0;
console.log(a)
}
}
<button onclick="imageswap()">GO</button><br>
<img id="IMAGE" width="100" height="200"></img>
Ok Few things you need to take care:
You are passing a within the function imageswap(a) and you are accessing a from the value passed within the function that'll be 0 all the time. Check https://jsfiddle.net/aegwj88g/
You are checking var a==0, var a==1 which is incorrect. It should be like if(a==0) or else if(a==1).
You are trying to assig value to a with var a + 1 which is also incorrect. Left hand side must be a valid variable other than the javascript tokens (check JS naming convention) which stores the value. it should be a=a+1 (or a+=1) just as you do in maths;
Check this fiddle:

How to display one image in loop?

I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>

Toggling between two images by clicking

Due to this link
I changed it to this one:
<html>
<head>
<script>
var toggleimage=new Array("p1.gif","p.gif")
//do not edit the variables below
var image_1=new Image()
var image_2=new Image()
image_1.src=toggleimage[0]
image_2.src=toggleimage[1]
var i_image=0
function testloading() {
isloaded=true
}
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
onload=testloading
</script>
<title>
</title>
<meta content="">
<style></style>
</head>
<body>
<img name="togglepicture" src="p1.gif" border="0">
</body>
</html>
when I click on the image p it will show me p1 and vice versa
Now I have problem image has a name:
<img name="togglepicture" src="p1.gif" border="0">
and it will get the name here:
document.togglepicture.src=toggleimage[i_image]
I want to have many images so I thaught I need to change the togglepicture to a variable
for example:
function toggle(a) {
if (isloaded) {
document.a.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
and for input forexample it will be toggle('nameofimage') and in the href it will be something like
<a href="javascript:toggle('pic1')">
I wasn't successful.How can I use this function when I have more than a picture to click?
I made a modular toogle, visible here: http://jsfiddle.net/Regisc/N7bgz/2/
Usage sample:
<img id="image1" src="http://dummyimage.com/50/f00/fff&text=a"
onclick='toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b",
"http://dummyimage.com/50/ab0/fff&text=c"]);' />
you can't use
document.a.src=toggleimage[i_image];
instead use
document.getElementById(a).src=toggleimage[i_image];
And you also need to add an id to your img element.
Something like the following should work for any number of images provided toggleimage is a contiguous array.
var toggleimage = ["p1.gif","p.gif"];
var toggle = (function() {
var count = 0;
var len = toggleimage.length;
var el = document.getElementsByName('togglepicture')[0]
return function() {
if (isloaded) {
el.src = toggleimage[count++ % len];
}
};
}());
I'm not entirely sure I got your question. Are you asking:
How to edit the function to allow toggling between more than just two images, or
How to edit the function to handle more than one set of toggle images?
Toggling between more than just two images
var toggleimage=new Array("p1.gif","p.gif","p2.gif","p3.gif","p4.gif")
var totalImages=4;
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>totalImages) {i_image=0}
}
How to edit the function to handle more than one set of toggle images?
call the JS function like this
<a href="javascript:toggle(this)">
And, in your JS function,
var id = div.id;
Use this in an if-else to determine which control called the function and accordingly which array of images to use.
function toggle(div)
{
var id = div.id;
if (isloaded)
{
if (id == 'myFirstToggleImageControl')
{
document.togglepicture.src=toggleimage[i_image];
}
else if (id == 'mySecondToggleImageControl')
{
document.togglepicture.src=toggleimageSource2[i_image];
}
}
i_image++
if (i_image>1) {i_image=0}
}
Note: You will want to use an independent counter for the second control. So, possibly i_image1 and i_image2
<html>
<head>
<script>
// images list (properties name must by equal to id of IMAGE html element)
var imageList={
image1: {
currentIndex:0,
images:["p1.gif","p.gif"]
}
};
// preloading images using closure (additionaly replace image URL's with image objects)
(function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
for(var i=0;i<imageList[p].images.length;i++) {
var img=new Image(),src=imageList[p].images[i];
(imageList[p].images[i]=img).src=src;
}
}
})();
function toogleImage() {
var info=imageList[this.id];
info.currentIndex++;
if(info.currentIndex===info.images.length)info.currentIndex=0;
this.src=info.images[info.currentIndex].src;
}
// setting start images
window.onload=function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
//try{
document.getElementById(p).src=imageList[p].images[0].src;
//}
//catch(ex){}
}
}
</script>
</head>
<body>
<img id="image1" onclick="toogleImage.call(this);"/>
</body>
</html>
http://jsfiddle.net/X4Q2m/

Categories

Resources