easier way to code series of images javascript - 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; };
});

Related

How to set src to each shuffled image in javascript?

I'm trying to shuffle images from array to a specific div.
<body>
<div id="set"></div>
</body>
<script>
var ArrayOfImages = ['bar.jpg',
'foo.jpg',
'koo.jpg',
'too.jpg'
];
var set = document.getElementById("set");
set.addEventListener("click", randomize, false);
ArrayOfImages.forEach(function(image) {
var elem = document.createElement('img');
elem.src = image;
set.appendChild(elem);
});
function shuffle(array) {
let counter = array.length;
// While there are elements in the array`enter code here`
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
function randomize() {
set.innerHTML = shuffle(ArrayOfImages);
}
</script>
Now the problem is, that innerHTML only changes the text of the image but cannot set an src to it. Though it does the shuffle.
Any help would be appreciated!
.innerHTML will change the actual HTML, not the images src which is what you want to change.
At the moment you are getting your image elements from your HTML using
document.getElementById('set)
however, you HTML can only have one element with the id set. Thus, you can use the class attribute instead to give multiple elements the identifier of 'set' and get all your image elements using:
document.getElementsByClassName('set')
which will return a collection of your HTML image tags. Now, to change each image's source you can loop over this collection or loop over your shuffled images and set each image's source.
See an example below for further clarification:
var img_elems = document.getElementsByClassName('set'); // Get all elements to set the image to
// To go into your randomize() function:
// Shuffled images returned via your shuffle() function
var shuffled_images = ['https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350', 'https://www.pandotrip.com/wp-content/uploads/2018/09/Seigantoji-Pagoda-and-Nachi-Falls-in-Nacho-Japan.jpg', 'https://www.elastic.co/assets/bltada7771f270d08f6/enhanced-buzz-1492-1379411828-15.jpg'];
for (var i = 0; i < shuffled_images.length; i++) {
img_elems[i].src = shuffled_images[i]; // Set the image to the src value.
}
/* Ignore this */
img {
height: 200px;
width: 200px;
}
<img src="" class="set" /><br />
<img src="" class="set" /><br />
<img src="" class="set" />
More clean and better way of doing it in vanilla javascript.
The issue was in your shuffle function.
var image_swap_tool = function(options){
var self = this;
self.ArrayOfImages = options.ArrayOfImages;
self.image_container_elem = document.getElementById("set");
self.image_container_elem.addEventListener("click", function(){
self.randomize();
});
}
image_swap_tool.prototype.create_image = function(){
var self = this;
var images = self.ArrayOfImages;
var image_container = self.image_container_elem;
image_container.innerHTML = '';
for(var i=0; i < images.length;i++){
var img = document.createElement('img');
img.setAttribute('src',images[i]);
image_container.appendChild(img);
}
};
image_swap_tool.prototype.shuffle = function(){
var self = this;
var images = self.ArrayOfImages;
let counter = images.length;
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = images[counter];
images[counter] = images[index];
images[index] = temp;
}
//Set new order back to images for next time
self.ArrayOfImages = images;
//Images are shuffled then append them again
self.create_image();
}
image_swap_tool.prototype.randomize = function(){
var self = this;
var image_container = self.image_container_elem;
self.shuffle();
}
var options = {};
options.ArrayOfImages = ['bar.jpg', 'foo.jpg', 'koo.jpg', 'too.jpg'];
var tool = new image_swap_tool(options);
tool.create_image();
Thanks

I don't how why my backgroundImage doesn't work

Why does my banner doesn't change her background? Please help me.
When I run the file the console tells me:
Uncaught TypeError: flechedroite.addEventListener is not a function
I really don't understand. I'm a beginner in Javascript so please explain me with kind words how I can fix this error :)
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url(" + bUrl + ")";
}
//image list
images[0] = 'images/image1.jpg';
images[1] = 'images/image2.jpg';
images[2] = 'images/image3.jpg';
flechedroite.addEventListener('click', function() {
for (var i = 0; i < images.length; i++) {
changeBackground(document.body, images[i]);
}
})
addEventListener should be called in window.onload or in $(document).ready()
Since getElementsByClassName returns an array, you need to use array index with flechedroite to add an event listener. i.e. flechedroite[0].addEventListener('click', function() {...});
You are calling changeBackground function in a loop to set the background image, effectively you will see only the last image from the array being set as background.
JS Code
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url("+bUrl+")";
}
//image list
images[0] = 'https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg';
images[1] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOGUhZo0Qe81U5qY_Z-seXgsD79LEEet832TVOlLMOEy10ZPsV';
images[2] = 'https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg';
window.onload = function(){
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var currentImageIndex = 0;
flechedroite[0].addEventListener('click', function() {
currentImageIndex = (currentImageIndex+1)%images.length;
changeBackground(document.body, images[currentImageIndex]);
})
}
The function getElementsByClassName returns a HTMLCollection, which is an array like structure that can contain multiple elements. So you need to use an index to access the elements contained in it.
So flechedroite.addEventListener results in an error but flechedroite[0].addEventListener should work
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
if you use 'getElementsByClassName' and you want to add an 'addEventListener', you can not do it in a 'generic' way: "flechedroite.addEventListener ('click', function () {}". You have to do this for each element:
var flechedroite = document.getElementsByClassName('fa fa-arrow-right');
//flechedroite contains all the elements that have the 'fa fa-arrow-right' classes
//on each element you have to add the "addEventListener"
for (var i = 0; i < flechedroite.length; i++) {
flechedroite[i].addEventListener('click', function() {
alert('flechedroite');
});
}
basic example JSFiddle1
a more advanced example
JSFiddle2

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.

(Javascript) SlideShow Not Working

Hello fellow stackoverflow members,
I've been trying to make a Slideshow. I've referenced from many other sites including this one but the pictures aren't showing up in the container element nor are the "prev" and "next" buttons functioning properly. I'd appreciate it if I got help! :)
my code:
var photos = newArray ();
photos[0] = "img/image(2).jpg";
photos[1] = "img/image(4).jpg";
photos[2] = "img/image(6).jpg";
photos[3] = "img/image(8).jpg";
photos[4] = "img/image(10).jpg";
photos[5] = "img/image(12).jpg";
photos[6] = "img/image(14).jpg";
photos[7] = "img/image(16).jpg";
photos[8] = "img/image(18).jpg";
photos[9] = "img/image(20).jpg";
photos[10] = "img/image(22).jpg";
photos[11] = "img/image(24).jpg"
//END OF PHOTOS ARRAY//
var i = 0;
var k = photos.length-1;
function next.onclick() {
var img= document.getElementById("image-container");
img.src = photos[i];
if (i < k ) {
i++;
}else {
i = 0; }
}
function prev.onclick() {
var img= document.getElementById("image-container");
img.src=photos[i];
if)i > 0) {i--;}
else {i = k; }
}
getImageArray = function(containerId) {
var containerElement = document.getElementById(container);
if (containerElement) {
var imageArray = containerElement.getElementById("container");
return photos[i];
} else {
return null;
}
}
this is what my slideshow looks like (it's broken)
http://prntscr.com/5dcfzq
The share button isn't important, I can make that work at least.
The main problem is that the pictures aren't showing and the back and foward buttons are messed up :'(
p.s ( I'm not sure if part of the reason is how I'm linking to the "next" or "back" functions with the div tag, because i'm this is how i'm doing it :
<div id = "back" onclick = "prev()"></div>
OK ... to summarize ...
1. var photos = newArray ();
There needs to be a space between new and Array, so ...
var photos = new Array();
2. function prev.onclick() { needs to be just function prev() {
3. Same with next.onclick() based on usage in HTML.
4. In prev() ... if)i > 0) {i--;} should be ...
if (i > 0) { i--; }
5. WRONG: Also in prev()' ... else should bei = k-1;`
6. DO NOT NEED Not sure why you have the getImageArray function at all.
7. This assumes there is an '' tag in the HTML.
UPDATE:
Here's the code that works ... this all goes in the body:
These are my assumptions in the body ...
<img id="image-container" />
<div id="back" onclick="prev()">Previous</div>
<div id="next" onclick="mext()">Next</div>
The script code MUST be at the end of the body ...
<script>
var photos = new Array ();
photos[0] = "img/image(2).jpg";
photos[1] = "img/image(4).jpg";
photos[2] = "img/image(6).jpg";
photos[3] = "img/image(8).jpg";
photos[4] = "img/image(10).jpg";
photos[5] = "img/image(12).jpg";
photos[6] = "img/image(14).jpg";
photos[7] = "img/image(16).jpg";
photos[8] = "img/image(18).jpg";
photos[9] = "img/image(20).jpg";
photos[10] = "img/image(22).jpg";
photos[11] = "img/image(24).jpg"
//END OF PHOTOS ARRAY//
// Here, I set the img variable so that it can be re-used.
// I also loaded the first image ...
var i = 0;
var k = photos.length-1;
var img = document.getElementById("image-container");
img.src = photos[i];
function next() {
img.src = photos[i];
if (i<k) {
i++;
} else {
i = 0;
}
}
function prev() {
img.src=photos[i];
if (i>0) {
i--;
} else {
i = k;
}
}
</script>

This code doesnt work. trying to use a loop to get the sizes of my images the first one comes but the others dont

$j(document).ready(<script type="text/JavaScript">
function getProps(){
var imgwidth = [];
var imgheight = [];
var w, h;
var width = document.getElementById('des').clientWidth;
var height = document.getElementById('des').clientHeight;
img = document.getElementById('des').getElementsByTagName('img').length;
w = document.getElementById('des').getElementsByTagName('img');
h = document.getElementById('des').getElementsByTagName('img');
for ( count = 0; count < img; count++){
imgwidth[count] = w.item(count).clientWidth;
imgheight[count] = h.item(count).clientHeight;
}
</script>);
I think this is what you want, I refactored your code a little:
function getProps()
{
var imgwidth = [];
var imgheight = [];
var images = document.getElementById('des').getElementsByTagName('img');
var count = images.length;
for ( i = 0; i < count; i++)
{
imgwidth[i] = images[i].clientWidth;
imgheight[i] = images[i].clientHeight;
}
console.log(imgwidth);
console.log(imgheight);
}
$(document).ready(function()
{
getProps()
});​
I have set up a jsfiddle for you to demonstrate this: http://jsfiddle.net/JbpdW/
Edit
If you use jQuery (what you obvilously do), you can simplify that process a little by using:
$("#des img").each(function(i)
{
imgwidth[i] = this.clientWidth;
imgheight[i] = this.clientHeight;
});
with jquery it is very short:
$j(function() {
var result=$j.map($('#des img'),function(el,i) {
var $el=$j(el); //optimize
return {width:$el.width(),height:$el.height()};
});
console.log(result);
});
please note that i used array of objects instead of two variables, it easer to work with one variable than with two :)
http://jsbin.com/uzikeh/2/edit

Categories

Resources