Show large picture from thumbnails in javascript - javascript

I have 4 thumbnails to the left, and when I click on one of them I waht to show a large picture to the right on the screen.
My problem is, that for some reason it shows 8 small thumbnails (first 4 and then 4 again). The first four ones are not clickable. The last four ones are clickable and correctly shows the larger image.
So, where does the first four thumbnails come from, and how do I get rid of them?
I have a transparant image (Picture.gif) that is the larger picture that is changed and shows the bigger versions of the thumbnails.
My html:
<body onLoad="init()">
<table class="planes">
<tr>
<td>
<ul>
<div id="thumb">
<li><img src="img/Plane1.jpg" alt="Plane1"></li>
<li><img src="img/Plane2.jpg" alt="Plane2"></li>
<li><img src="img/Plane3.jpg" alt="Plane3"></li>
<li><img src="img/Plane4.jpg" alt="Plane4"></li>
</div>
</ul>
</td>
<td>
<img class="pic" id="main" src="img/Picture.gif" alt="">
</td>
</tr>
</table>
My javascript:
var images= new Array('img/Plane1.jpg', 'img/Plane2.jpg', 'img/Plane3.jpg', 'img/Plane4.jpg');
var imgList = new Array();
function init()
{
for (var i=0; i<images.length; i++)
{
imgList[i] = new Image();
imgList[i].src = images[i];
document.getElementById('thumb').appendChild(imgList[i]);
imgList[i].addEventListener("click", swap, false)
}
}
function swap(evtObj)
{
var imgfile = evtObj.target.getAttribute('src');
var mainTag = document.getElementById('main');
mainTag.src = imgfile;
}

In this line:
document.getElementById('thumb').appendChild(imgList[i]);
You are appending the image to the 'thumb' list again. But these are the ones you want to keep, as they have the eventListener attached to them.
You need to remove the tags from your html code to achieve the desired result.
<li><img src="img/Plane1.jpg" alt="Plane1"></li>
<li><img src="img/Plane2.jpg" alt="Plane2"></li>
<li><img src="img/Plane3.jpg" alt="Plane3"></li>
<li><img src="img/Plane4.jpg" alt="Plane4"></li>

The first 4 images are the ones you have in your static html code. The next 4 are the dynamic generated from javascrip. Just remove the images inside thumb from your html code.

The images are both in your html, and also created in javascript.
The line document.getElementById('thumb').appendChild(imgList[i]); adds each image specified in the images array of your javascript to the page.
I suggest you will want to remove the ones in your html - simply remove the <li> tags and the images that are within them.
After taking out the unneeded tags, your HTML should look something like this:
<body onLoad="init()">
<table class="planes">
<tr>
<td>
<div id="thumb">
</div>
</td>
<td>
<img class="pic" id="main" src="img/Picture.gif" alt="">
</td>
</tr>
</table>

First, div cannot be a child of ul and second you shouldn't really use tables for layout (unless making an email template).
If you are just trying to change the src of the main image on the click of the thumbnails, you can use the following js:
var images = new Array('img/Plane1.jpg', 'img/Plane2.jpg', 'img/Plane3.jpg', 'img/Plane4.jpg'),
thumbnails = document.getElementById('thumb').getElementsByTagName('img'),
mainImage = document.getElementById('main');
for (i = 0; i < thumbnails.length; i++) {
setClickFunction(i);
}
function setClickFunction(currentIndex) {
thumbnails[currentIndex].onclick = function() {
mainImage.src = images[currentIndex];
};
}
Example
Using links for your large images instead of an array

Related

JQuery also loaded by hosting site, events run multiple times

After trying several lightbox variations and in the interest of getting back in practice and learning JQuery, decided to try coding my own http://walczak.000webhostapp.com/index.html. The hosting site for a project I'm working on looks to also be loading some form of JQuery. The behavior I'm seeing happens on the 3D pages where I need to present a gallery of images. The first time a gallery is opened, both clicking on a thumbnail image and using the Next / Previous buttons works as expected. However when a second gallery instance is opened, when using the Next / Previous buttons, every other image seems to be shown. 3rd time, every 3rd image. Debugging shows that JQuery is running multiple times. I have tried suggestions from click() event is calling twice in jquery with no success.
Also help with why a thumbnail needs to be clicked before the Next / Previous buttons will work (did not have this problem at first) and what I may have missed to solve the dreaded TypeError cannot read property inside the document.ready function on the thumbnail array would be appreciated. relevant code is:
On main page
<div class="boxback">
<div class="box">
<table>
<tr>
<td><a id="prev" href="#"><img class="galleryNav" src="./backgrounds/buttons/lightbox/back.png"></a></td>
<td><img id="imgbox" src="" alt=""></td>
<td><a id="next" href="#"><img class="galleryNav" src="./backgrounds/buttons/lightbox/forward.png"></a></td>
</tr>
<tr>
<td></td>
<td><p id="caption"></p></td>
<td></td>
</tr>
</table>
<div id="thumbs"></div>
<a id="myClose" href="#"><img src="./backgrounds/buttons/lightbox/close.png"></a>
</div>
</div>
...
Loaded content
<ul class="thumbsdiv">
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gearsmain.png" alt="Original DaVinci drawing" data-index=0></a></li>
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gears01.png" alt="" data-index=1></a></li>
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gears02.png" alt="" data-index=2></a></li>
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gears03.png" alt="" data-index=3></a></li>
(abbreviated ...)
</ul>
JQuery
var mypath = "";
var myindex = Number(0);
//var imgs = [];
$(document).ready(function()
{
$(".overlay").click(function()
{
mypath = $(this).attr("data-gallery");
mypath += " .thumbsdiv";
$("#thumbs").load(mypath);
$(".boxback").css("display","block");
$(".box").css("display","inline-block");
$("#imgbox").attr("src",$(this).attr("data-image"));
$("#imgbox").attr("alt",$(this).attr("data-alt"));
$("#caption").text($(this).attr("data-alt"));
myindex = Number($(this).attr("data-index"));
do{
if (document.readyState === "complete")
{ $(document).on("click",".thumbnail",thumbClick);
$(document).on("click","#prev,#next",nextImg);
$(".thumbnail")[myindex].trigger("click");
//$('[data-index = "0"]').click();
}
} while(document.readyState !== "complete");
})
});
function thumbClick()
{
// $("#imgbox").attr("src","");
// $("#imgbox").attr("alt","");
$("#caption").text("");
$("#imgbox").attr("src",$(this).attr("src"));
$("#imgbox").attr("alt",$(this).attr("alt"));
myindex = Number($(this).attr("data-index"));
$("#caption").text($(this).attr("alt"));
$(".thumbnail").css({"border-style":"none"});
$(this).css({"border-style":"solid",
"border-color":"#000",
"border-size":"1px"});
event.stopImmediatePropagation();
};
//$("#prev,#next").click(function nextImg()
function nextImg()
{
var imgs = $(".thumbnail");
if ($(this).attr("id") == "next")
{myindex++;}
else {myindex--;}
if (myindex <= -1)
{myindex = imgs.length - 1;}
if (myindex >= imgs.length)
{myindex = 0;}
imgs[myindex].click();
};

Insert image src into Javascript Array by Class Name

I'm trying to create a JavaScript that will randomize images on page refresh. I'm not really familiar with JS so I've been having a bit of trouble.
I've succeeded in building a successful program by hard coding the image url sources into the JS array, but this is not a possibility for what I am coding this for because the user will dictate what set of images will display. The user will not have access to the JS. So the array would get the image sources from the html. What I've been trying to do is use "getElementByClassName" and insert into the array by for loop. But it doesn't seem to be working. I'm sure there is a more efficient way to do this as well, so feel free to enlighten me.
Here is the code I have so far:
<!-- Images to put into JS Array -->
<img class="header" src="/image1.jpg" style="display: none;" />
<img class="header" src="/image2.jpg" style="display: none;" />
<img class="header" src="/image3.jpg" style="display: none;" />
<!-- Image placeholder -->
<img src="/image1.jpg" id="rotate" />
And the JavaScript in a separate document:
// Javascript code
window.onload = chooseHeader;
var imgs = document.getElementsByClassName("header");
var headers = new Array();
for (var i = 0; i < imgs.length; i++) {
headers.push(imgs[i].src);
}
function chooseHeader() {
rand = Math.floor((Math.random() * headers.length));
document.getElementById("rotate").src = headers[rand];
}
Any advice will be appreciated!
Your code is probably running before the DOM has loaded.
You don't actually need an Array for this, and since getElementsByClassName returns a "live list", you can fetch the images before they exist, and they'll appear when they're loaded in the document.
So if that's the case, a solution is to get the src directly from imgs.
window.onload = chooseHeader;
// live list
var imgs = document.getElementsByClassName("header");
function chooseHeader() {
var rand = Math.floor((Math.random() * imgs.length));
document.getElementById("rotate").src = imgs[rand].src;
}
<img class=header src="https://dummyimage.com/50/f00/fff.jpg">
<img class=header src="https://dummyimage.com/50/0f0/fff.jpg">
<img class=header src="https://dummyimage.com/50/00f/fff.jpg">
<br><br>
Rotate:
<br><br>
<img id=rotate src="">

Load and play a gif with javascript onclick event

On my website I have three images 1.png, 2.png and 3.png. When I click on 1.png, I want the animated gif 1a.gif to be loaded and shown/updated in the img tag located in <div id="container">. When I click on 2.png, 2a.gif should be displayed (while 1a.gif vanishes) and so on... This is my code:
<html>
<body>
<div>
<img src="1.png" onclick="document.getElementById('img').src = '1a.gif'" />
<img src="2.png" onclick="document.getElementById('img').src = '2a.gif'" />
<img src="3.png" onclick="document.getElementById('img').src = '3a.gif'" />
</div>
<div id="container">
<img id="img" src="1a.gif" />
</div>
</html>
</body>
It is working, however unreliable (tested with firefox and chrome)! When I refresh the html page and click on 1.png, than on 2.png ... suddendly at one point only the first frame of the animated gif is shown. I have to click on the same image (1,2 or 3.png) again in order to make the gif run. Why? I am looking for a light weight javascript solution without jquery. I am just asking myself why the gif is not played properly once I click on the image.
As a side note: It would be nice to show a loading image while the gif (5 MB) is loading. I failed to achive that using css:
#container {background:url('loading.png') no-repeat; }
In this case the loading image doesn't show up at all. Probably because I am updating directly from one (e.g. 1a.gif) to another (e.g. 2a.gif).
Showing it right before loading the gif did not help as well:
<img src="1.png" onclick="document.getElementById('img').src = 'loading.png';
document.getElementById('img').src = '1a.gif'" />
There are many ways of implementing this kind of thing, but to keep in line with how you're doing it, you'll want to hook into the onload event of the img.
Note that in this snippet, I don't have access to your GIFs, so I'm using the dummyimage.com service, which is pretty fast, so you don't see the "loading" for very long.
window.onload = function() {
var img = document.getElementById('img');
var container = document.getElementById('container');
var showImage = function showImage() {
img.style.display = "inline";
container.style.backgroundImage = "";
};
img.addEventListener('load', showImage);
img.addEventListener('error', showImage);
var thumbs = document.getElementsByClassName('thumb');
for (var i = 0, z = thumbs.length; i < z; i++) {
var thumb = thumbs[i];
var handler = (function(t) {
return function clickThumb() {
container.style.backgroundImage = "url('https://dummyimage.com/500x500/000/fff.gif&text=loading')";
img.style.display = "none";
img.src = t.dataset['image'];
};
})(thumb);
thumb.addEventListener('click', handler);
}
};
<div>
<img src="1.png" class="thumb" data-image="https://dummyimage.com/500x200/000/fff.gif" />
<img src="2.png" class="thumb" data-image="https://dummyimage.com/200x200/000/fff.gif" />
<img src="3.png" class="thumb" data-image="https://dummyimage.com/500x500/000/fff.gif" />
</div>
<div id="container">
<img id="img" class="main" />
</div>
This happens bacause the second img is not loaded yet!
I suggest you to put the 2 img in 2 different divs and the use javascript to hide/show the entire div!

From the last slide to the first slide with slideUp/slideDown

I made my slider but it's acting wierd when it reach the last slide and have to start again on the first. Until getting to the last slide it slides upwards, but when it has to go to the first it does it downwards. And it kind a misses the first one. I mean - it shows it (even downwards), but on my pagination dots it doestn't add class .selected to the first one. After that it acts normally again until the next cycle.
Why is that two things happening. I've tried to change the if(active_slide.index() == last_slide.index()) with if(active_slide.next().length == 0) /and < /; if(active_slide.is(last_slide)) ... it didn;t help.
Here is jsfiddle http://jsbin.com/iwiroq/4/edit.
Building on #yabol's answer, I've built a minimal example with a rolling image list
HTML:
<div class="image-slider">
<ul>
<li><img src="http://lorempixel.com/400/200/sports" alt="" /></li>
<li><img src="http://lorempixel.com/400/200/food" alt="" /></li>
<li><img src="http://lorempixel.com/400/200/city" alt="" /></li>
<li><img src="http://lorempixel.com/400/200/nature" alt="" /></li>
</ul>
</div>
JS:
var image_list = $('.image-slider li');
image_list.hide();
var first_child = '.image-slider li:first-child';
var last_slide = $('.image-slider li:last-child');
var last_index = last_slide.index();
var active_slide = $(first_child);
active_slide.show();
setInterval(next, 5000);
function next(){
active_slide.slideUp();
if (active_slide.index() >= last_index)
$(first_child).insertAfter(active_slide);
active_slide = active_slide.next();
active_slide.slideDown();
}
JSFiddle or Tinker for playing.
The reason it slides downwards instead of upwards is because first element of the list is higher in dom tree than the last one. You can work it around by adding first element also as the last one, and the last one element gets loaded you swap it with first.

Javascript multiple slideshow

I have created an HTML file which uses java script to display images randomly displayed in 3 div tags. On click the images move left or right. It works fine until I use single slideshow in the page, but creates problem when I try multiple slideshows on the same page.
Here is the code for one slide show :
**<script>
currentIndx = 2;
MyImages=new Array();
MyImages[0]='1images2.jpeg';
MyImages[1]='1images3.jpeg';
MyImages[2]='1images4.jpeg';
MyImages[3]='artwork.jpg';
MyImages[4]='1images5.jpeg';
imagesPreloaded = new Array(4)
for (var i = 0; i < MyImages.length ; i++)
{
imagesPreloaded[i] = new Image(120,120)
imagesPreloaded[i].src=MyImages[i]
}
/* we create the functions to go forward and go back */
function Nexter()
{
if (currentIndx<MyImages.length-1){
alert(currentIndx);
document.leftimg.src=document.middleimg.src
document.middleimg.src=document.rightimg.src
document.rightimg.src=imagesPreloaded[++currentIndx].src
}
else {
alert("In nexter else")
currentIndx=0
document.leftimg.src = document.middleimg.src
document.middleimg.src = document.rightimg.src
document.rightimg.src = imagesPreloaded[currentIndx].src
}
writeImageNumber();
}
function Backer()
{
if (currentIndx>0)
{
--currentIndx;
alert("In Backer If");
document.rightimg.src=document.middleimg.src
document.middleimg.src=document.leftimg.src
document.leftimg.src=imagesPreloaded[currentIndx].src
}
else
{
currentIndx = MyImages.length-1
alert(MyImages.length +"else");
document.rightimg.src = document.middleimg.src
document.middleimg.src = document.leftimg.src
document.leftimg.src = imagesPreloaded[currentIndx].src
}
writeImageNumber();
}
/*###### function to reload the images and text when refresh is pressed ##### */
function setCurrentIndex()
{
currentIndx=0;
document.theImage.src=MyImages[0];
document.form1.text1.value=Messages[0];
writeImageNumber();
}
</script>
<body onload="setCurrentIndex();automaticly()">
<!-- start of form for image slide show ####################### -->
<div id ="left" style="float:left">
<a href="#" onclick="Backer()" ><img src="1images2.jpeg" width="265" height="262"
border="0" name="leftimg"></a>
</div>
<div id ="middle" style="float:left">
<a href="#" onclick=""><img src="1images3.jpeg" width="265" height="262"
border="0" name="middleimg"></a>
</div>
<div id ="right" class="compimg" style="float:left">
<a href="#" onclick="Nexter()" ><img src="1images4.jpeg"
width="265" height="262" alt="" border="0"name="rightimg"></a>
</div>
<!-- end of form for image slide show ####################### -->**
Any suggestions...
You haven't wrapped your script in any javascript class(object) so all variables you are using have global scope(page level). I guess your variables are over written if you try to use it multiple time.
You can get better answer if you post HTML markup of how you are trying to create multiple slideshow in single page...

Categories

Resources