Only one image appears in an array of 3 images in JavaScript - javascript

<img id="opeth"> </img>
<script type="text/javascript">
var gearpics = [];
document.getElementById("opeth").innerHTML = gearpics;
var prs = new Image();
prs.onload = function() {
};
prs.src = src
var prs2 = new Image();
prs2.onload= function() {
};
prs2.src = src
var prs3 = new Image();
prs3.onload= function() {
};
prs3.src = src
function insert() {
gearpics.push(document.getElementById('opeth').src = prs.src);
gearpics.push(document.getElementById('opeth').src = prs2.src);
gearpics.push(document.getElementById('opeth').src = prs3.src);
}
</script>
This is my code. When I run it, and press the "Show pictures" button, only the third picture (id=prs3) appears. I want all of them to show up.

You are using the same ID for your 3 pictures:
gearpics.push(document.getElementById('opeth').src = ...);
ID should be unique in HTML document.

Related

Javascript - Editing image every minute, updating image

I'm trying to make a Generator where a user can insert their Battlenet Name (name) and have it output their Emblem (data.characters[2].embemBackground) plus their light level (data.characters[0].light) on the image too.
Then, I want the user to be able to use an image link, such as: http://www.test.com/image.png
And have it get updated automatically with the stats from the API, so it overwrites the image without changing the URL.
Result:
I used html2canvas capture to get the image itself from (#character2img)
I do realize this is probably not the best way to approach this.
Code:
const { Client } = require('destiny2');
const client = new Client('apiKey');
const html2canvas = require('html2canvas');
window.memberName = function(){
var pName = document.getElementById("pageheader");
var pLl = document.getElementById('LightLevel');
var pLl2 = document.getElementById('LightLevel2');
var pLl3 = document.getElementById('LightLevel3');
var gT = document.getElementById('Guardian');
var gT2 = document.getElementById('Guardian2');
var gT3 = document.getElementById('Guardian3');
var divI = document.getElementById('character1img');
var name = document.getElementById('search').value;
client.getProfile(name, '4')
.then(data => console.log(data));
client.getProfile(name, '4').then(data => {
pName.appendChild(document.createTextNode(`${data.profile.displayName}`));
// Character 1
// Emblem Image
var elem = document.createElement("img");
elem.src = `http://bungie.net${data.characters[0].embemBackground}`;
var image = document.getElementById('character1img').appendChild(elem);
// Light Level
pLl.appendChild(document.createTextNode(`♦ ${data.characters[0].light}`));
// Character 2
// Emblem Image
var elem = document.createElement("img");
elem.src = `http://bungie.net${data.characters[1].embemBackground}`;
var image2 = document.getElementById('character2img').appendChild(elem);
// Light Level
pLl2.appendChild(document.createTextNode(`♦ ${data.characters[1].light}`));
// Character 3
// Emblem Image
var elem = document.createElement("img");
elem.src = `http://bungie.net${data.characters[2].embemBackground}`;
var image2 = document.getElementById('character3img').appendChild(elem);
// Light Level
pLl3.appendChild(document.createTextNode(`♦ ${data.characters[2].light}`));
});
}
window.screenshot = function(){
html2canvas(document.querySelector("#character1img"), {allowTaint : true}).then(canvas => {
document.body.appendChild(canvas)
});
}
window.screenshot2 = function(){
html2canvas(document.querySelector("#character2img"), {allowTaint : true}).then(canvas => {
document.body.appendChild(canvas)
});
}
window.screenshot3 = function(){
html2canvas(document.querySelector("#character3img"), {allowTaint : true}).then(canvas => {
document.body.appendChild(canvas)
});
}

How do I switch lights on a traffic light sequence?

I'm trying to make a traffic light sequence so that when I press the "change lights" button its supposed to change each time it has been pressed. However, I've the made the code appear with the red light but when I press the "change lights" button it won't change to amber and the other light sequence.
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Light</h1>
<button type="button" onclick="changeLights"()>Change Lights </button>
<script>
var traffic_light = new Array(3)
var traffic_lights = 0
function lights(){
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_red.jpg";
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_redAmb.jpg";
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_green.jpg";
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_amber.jpg";
}
function changeLights() {
document.traffic_light_images.src = traffic_light[traffic_lights].src
traffic_lights++
if(traffic_lights > 3) {
traffic_lights = 0;
}
}
</script>
<img src = "traffic_light_red.jpg" name "traffic_light_images" height = "500" width = "800">
</body>
</html>
You put the parenthesis outside the quotes onclick="changeLights"()
You don't have an = after the name attribute - do you see it's not the same as the others and not valid html?
You are trying to select a DOM Node with JS that is run before it is inserted in the document (your script tag executes above the image)
You are setting width and height without a unit, and setting width and height like that is not recommended for responsiveness (just advice, not an error). In my example I just let the image naturally fit without specifying.
You are not properly inserting new items into the array, instead you reassigned the array to a new image four times (use push)
var traffic_light = [];
var traffic_lights = 1;
function initLights() {
var image;
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-light-red.jpg";
traffic_light.push(image);
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-lights-red-amber.jpg";
traffic_light.push(image);
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-lights-amber.jpg";
traffic_light.push(image);
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-lights-green.jpg";
traffic_light.push(image);
}
function changeLights() {
document.traffic_light_images.src = traffic_light[traffic_lights].src;
traffic_lights++;
if (traffic_lights > 3) {
traffic_lights = 0;
}
}
initLights();
<button type="button" onclick="changeLights()">Change Lights </button>
<img src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg" name="traffic_light_images">
However there is no need to create an new image object just to switch the source and your code can be simplified:
const imageBasePath = 'http://www.drivingtesttips.biz/images/';
const traficLights = [
'traffic-light-red.jpg',
'traffic-lights-red-amber.jpg',
'traffic-lights-amber.jpg',
'traffic-lights-green.jpg',
];
const trafficLightImage = document.querySelector('.traffic-light-image');
let trafficLightIndex = 1;
function changeLights() {
trafficLightImage.src = imageBasePath + traficLights[trafficLightIndex];
trafficLightIndex++;
if (trafficLightIndex === traficLights.length) {
trafficLightIndex = 0;
}
}
<button type="button" onclick="changeLights()">Change Lights</button>
<img src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg" class="traffic-light-image" />

easier way to code series of images javascript

In the code below, I've successfully made it so when someone clicks on a thumbnail of a picture, it's full picture will come up in the target.
I was wondering if anyone knew of a nicer way to create onclick events for multiple thumbnails I would like to make this expandable.
Also, please consider only javaScript answers as I don't write in jQuery (yet!).
var img = document.getElementById("galleryImg");
var thumb = document.getElementsByClassName("imgThumb");
var p0 = "https://dl.dropboxusercontent.com/u/89495286/test/images/pic1.png";
var p1 = "https://dl.dropboxusercontent.com/u/89495286/test/images/pic2.png";
var p2 = "https://dl.dropboxusercontent.com/u/89495286/test/images/pic3.png";
var p3 = "https://dl.dropboxusercontent.com/u/89495286/test/images/pic4.png";
var p4 = "https://dl.dropboxusercontent.com/u/89495286/test/images/pic5.png";
var p5 = "https://dl.dropboxusercontent.com/u/89495286/test/images/pic6.png";
var pArray = [p0, p1, p2, p3, p4, p5]
img.src = pArray[0];
thumb[0].onclick = function(){pic0()};
function pic0(){img.src = pArray[0]};
thumb[1].onclick = function(){pic1()};
function pic1(){img.src = pArray[1]};
thumb[2].onclick = function(){pic2()};
function pic2(){img.src = pArray[2]};
thumb[3].onclick = function(){pic3()};
function pic3(){img.src = pArray[3]};
thumb[4].onclick = function(){pic4()};
function pic4(){img.src = pArray[4]};
thumb[5].onclick = function(){pic5()};
function pic5(){img.src = pArray[5]};
Assuming that you'll have the same amount of elements in pArray as you would have thumbnails, you would do this:
Array.prototype.forEach.call(thumb, function(thumbItem, index) {
thumbItem.onclick = function() {
img.src = pArray[index];
};
});
It iterates through the thumbnails, attaching the onclick handler and assigning the main image with the corresponding image based on the element's index.
You could use the loop for any array, we usually use the for loop for related arrays.
for (var i = 0; i < thumb.length; i++) {
thumb[i].src = pArray[i]; // change if different src
thumb[i].onclick = function() { img.src = this.src; };
}
Try on: https://jsfiddle.net/Zay_DEV/8r1gqnfx/
var img = document.getElementById("galleryImg");
var thumb = document.getElementsByClassName("imgThumb");
var pArray = [
"https://dl.dropboxusercontent.com/u/89495286/test/images/pic1.png",
"https://dl.dropboxusercontent.com/u/89495286/test/images/pic2.png",
"https://dl.dropboxusercontent.com/u/89495286/test/images/pic3.png",
"https://dl.dropboxusercontent.com/u/89495286/test/images/pic4.png",
"https://dl.dropboxusercontent.com/u/89495286/test/images/pic5.png",
"https://dl.dropboxusercontent.com/u/89495286/test/images/pic6.png"
]
for (var i = 0; i < thumb.length; i++) {
thumb[i].src = pArray[i];
thumb[i].onclick = function() { img.src = this.src; };
}
thumb[0].onclick();
#galleryImg { max-height: 25vh; }
.imgThumb { width: 100px; height: 50px; }
<img id="galleryImg"/>
<br />
<img class="imgThumb"/>
<img class="imgThumb"/>
<img class="imgThumb"/>
<img class="imgThumb"/>
<img class="imgThumb"/>
<img class="imgThumb"/>
You iterate over the array, however, using a loop alone will not completely fix the problem, because you're assigning a function inside the loop, which means any outside variables could change before the onclick executes.
So what you need is a closure.
Create a function that sets the onclick callback
Call that function in a loop.
Here's an example:
function setOnClick(element, imgSrc) {
element.onclick = function() { img.src = imgSrc; };
}
for (var i = 0; i < thumb.length; i++) {
setOnClick(thumb[i], pArray[i]);
}
This functionality is very common, so it has also been implemented by Array#forEach:
pArray.forEach(function(imgSrc, index) {
thumb[index].onclick = function() { img.src = imgSrc; };
});

Advice to create a code for selectin image

i would like to create a function (javascript) where some images are displayed on the screen and the user can chose one of them by simply clicking over it. Once chosen, the src of the picture will be stored in a var. So far i made an images array, but i dont know if it's the right way to proceed, do any of you have some tips? Thanks all!
<script typre="text/javascript">
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
for (var i = 0; i < img.length; i++) {
document.body.appendChild(img[i]);
};
</script>
Try this :
var img = new Array();
img[0] = new Image();
img[0].src = "http://dummyimage.com/200/000/fff&text=Img0";
img[1] = new Image();
img[1].src = "http://dummyimage.com/200/000/fff&text=Img1";
img[2] = new Image();
img[2].src = "http://dummyimage.com/200/000/fff&text=Img2";
for (var i = 0; i < img.length; i++) {
var imagetag = document.createElement("img");
var onclick = document.createAttribute("onclick");
onclick.value = "myfun("+i+")";
var sorc = document.createAttribute("src");
sorc.value = img[i].src;
var id = document.createAttribute("id");
id.value = "my_image"+i;
imagetag.setAttributeNode(onclick);
imagetag.setAttributeNode(sorc);
imagetag.setAttributeNode(id);
document.body.appendChild(imagetag);
};
function myfun(i) {
var src = document.getElementById('my_image'+i).src;
//you can do anything with 'src' here
document.getElementById('demo').innerHTML = src; //for demo purpose
}
<p id="demo"></p>

How to Change the Source of an Image W/JS

I have to change the src of an image using java script and I am pretty sure i hit a road block, in the html I have 3 li elements and in the id is the source of the mouseenter img. I feel like I am close but so far. Heres my code so far. Thanks for any help!
Javascript:
var $ = function (id) {
return document.getElementById(id);};
window.onload = function () {
var links = document.getElementsByTagName("li"),
imgElements = document.getElementsByTagName("img"),
imgNode,
i,
URLone,
URLtwo,
link,
image;
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
}
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
HTML ::
<body>
<section>
<h1>Ram Tap Combined Test</h1>
<ul id="image_rollovers">
<li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li>
<li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li>
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
</ul>
</section>
Working jQuery :
$(document).ready(function() {
$("#image_rollovers img").each(function() {
var oldURL = $(this).attr("src"); // gets the src attribute
var newURL = $(this).attr("id"); // gets the id attribute
// preload images
var rolloverImage = new Image();
rolloverImage.src = newURL;
$(this).hover(
function() {
$(this).attr("src", newURL); // sets the src attribute
},
function() {
$(this).attr("src", oldURL); // sets the src attribute
}
); // end hover
}); // end each
}); // end ready
for (i = 0; i < imgElements.length; i++) {
(function(imgNode) {
imgNode.addEventListener("mouseenter", function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}, false);
imgNode.addEventListener("mouseout", function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
}, false);
})(imgElements[i]);
}
A couple of problems in your code.
First for loop closing right away, instead should close after your
imgNode.mouseout function
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
}
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
Last for loop runs 6 times but there are only 3 tags in html. When it coming to loop no. 3 it doesn't get any value for link.src.
Also links variable provides a collection of 'li' tags and not 'img', last for loop requires src from link.src which doesn't have any value, need to change
var links = document.getElementsByTagName("li"),
to
var links = document.getElementsByTagName("img"),
Try that. Hopefully after correcting above errors your code should work.

Categories

Resources