JS photogallery. Getting the big image to display and and thumbnails to be clickable - javascript

I have a quick issue that I need help with and hoping a fresh set of eyes can pinpoint my issue. I have a photo gallery and I want to display a larger image of the thumbnail when it is clicked. The thumbnails images show up fine at the bottom but are not clickable and the main (or larger image) does not show up. I am using an external .js file. I will upload the HTML also, and maybe some one can point me in the right direction and help me understand what I am overlooking.
<!doctype html>
<html>
<head>
<title>Photo Gallery Final Project</title>
<meta charset = "UTF-8">
<link rel = "stylesheet" href = "gallery.css">
</head>
<body>
<div class = "main">
<div class = "wrapper">
<div id = "largeImage">
<img src = "images/machine_1_big.jpg" alt = "machining image" width = "920" height = "400" id = "myImage" class = "border"/>
</div>
<div class = "thumbnail">
<img src="machine_1.jpg" alt = "machining lathe" id="machine_1"/>
<img src="machine_2.jpg" alt = "machining lathe" id="machine_2"/>
<img src="machine_3.jpg" alt = "machining lathe" id="machine_3"/>
<img src="machine_4.jpg" alt = "machining lathe" id="machine_4"/>
<img src="machine_5.jpg" alt = "machining lathe" id="machine_5"/>
<img src="machine_6.jpg" alt = "machining lathe" id="machine_6"/>
</div>
</div>
</div>
<script src = "gallery.js"></script>
</body>
</html>
//this will load the gallery in the browser and enable the gallery function
//window.onload = gallery;
//gallery funtion declared
function gallery(){
//variable allGalleryImages created. This is where all the images will be held
var allGalleryImages = document.images;
//for loop declared for the image array
for(var i = 0; i < allGalleryImages.length; i++){
if(allGalleryImages[i].id.indexOf("small") > -1){
//this will add a listener to the thumb images
allGalleryImages[i].onclick = imgChanger;
}
}
}
//this is the image changer function
function imgChanger(){
//this will change the src attribute value of the large image.
//document.getElementById('myImage').src ="images/"+this.id+"_big.jpg";
document.getElementById('myImage').src = " " + this.id +"_big.jpg";
}

I used JQuery. Did not have to change your HTML. And there is no reason to make and array of all the thumbnails.
$(document).ready(function() {
$(".thumbnail img").on("click", function() {
imgChanger($(this).attr("src"));
})
//this is the image changer function
function imgChanger(theSRC) {
//this will change the src attribute value of the large image.
//document.getElementById('myImage').src ="images/"+this.id+"_big.jpg";
var beforeJPG = theSRC;
console.log(beforeJPG);
beforeJPG = beforeJPG.substring(0, beforeJPG.length-4);
console.log(beforeJPG + "_big.jpg");
$("myImage").attr("src", beforeJPG + "_big.jpg");
}
})
Fiddle: https://jsfiddle.net/6v8arhp2/
Get the src of the clicked image
Chop off ".jpg"
Add "images/" to the front, add "_big.jpg" to the back
Change src of #myImage
** Of course your images are not inside JSFiddle so you cannot see it work, but the console logs show the transformation.

Related

How i can change img source ? souppose i have 10 images to change on same source

I want to make a button that simply change photo src from given src of image
<div id="main_photo">
<img class="card-img-top" src="/img/new0.JPG" alt="Avatar" >
</div>
I have new1.JPG to new6.JPG photo which should be changed on this image source on click of a button
All photos are in my /img/ folder
And here is my HTML code for the button to change src with onclick.
<button id="changeimg" > Change </button>
As #Teemu said (in comments), if you have the list of the new images you want to change to, you can do it by js code.
<div id="main_photo">
<img class="card-img-top" id="mainImage" src="/img/new0.JPG" alt="Avatar" >
</div>
<button id="changeimg" onclick="changeImage()"> Change </button>
<script>
var imageIndex = 0;
var imageCount = 6; // Can be also an array of images names ["/img/new0.JPG", "/img/new1.JPG", ..., "/img/new6.JPG"]
function changeImage() {
var imageContainer = window.getElementById("mainImage");
imageContainer.src = "/img/new" + (imageIndex++) + ".JPG";
// Make sure you validate the counter so it won't overflow
}
</script>
I have a demo for you if you have the list of images. And I believe that you can have that by simple code to get all images in your local folder.
const listSources = [
'/img/new0.JPG',
'/img/new1.JPG',
'/img/new2.JPG',
'/img/new3.JPG',
'/img/new4.JPG',
'/img/new5.JPG',
'/img/new6.JPG',
]
var currentIndex = 0;
$('#changeimg').click(function() {
// increase index to show the next image
currentIndex++;
// reset if reach the last image
if (currentIndex == listSources.length) currentIndex = 0;
// set image src
$('#main_photo>img').first()
.attr('src', listSources[currentIndex])
.attr('alt', listSources[currentIndex]); // change alt to show changes in demo
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeimg">Change</button>
<div id="main_photo">
<img class="card-img-top" src="/img/new0.JPG" alt="/img/new0.JPG">
</div>

href javascript is not working on my image

I'm adding images stored in firebase to my html page from the database. That works and the image shows up, but I am unable to make the href property work on the img element. I want it to be clickable. Suggestions what I am doing wrong here?
var img = document.createElement("img");
img.src = snapshot.child("urlToImage " + (i) + " Content").val();
img.href = snapshot.child("urlToImage " + (i) + " Content").val();
img.height = 30;
img.width = 30;
contentA[i].appendChild(img);
Clickable image
function clickMe(){
alert('Clicked!');
}
<!DOCTYPE html>
<html>
<body>
An image as a link:
<a onclick="clickMe()">
<img src="https://s3.eu-central-1.amazonaws.com/live-resource/productCategories/HF-AT/HF_PRINT_WEB_F781A5E7-1575-4D81-8317-BC51C8653EBB.jpeg" border="0" alt="W3Schools" src="logo_w3s.gif" width="100" height="100">
</a>
</body>
</html>
You have to wrap the img element in an a tag.
<a href='urlToImage'><img src='urlToImage' /></a>
You can of course have an href attribute on an img if you want to, it just doesn't have any special default meaning to browsers like it would on an anchor
Is href a valid attribute of img? I've never seen that before. If you want it to be clickable just wrap it in a anchor.

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!

How to switch 4 images using a button

<html>
<head>
<title>How To Insert an Image</title>
<script>
function changeImage(){
var img = document.getElementById('image');
image.src='image4.jpg';
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
I am quite new to Javascript so please dont be too harsh. Basically im trying to switch from one picture to another using a button. So far with this code i have only managed to do 2 images but when i try to add a 3rd or 4th the first image messess up. I was hoping if someone could help me fix this problem.
Here's simplest approach the I used before, for two images. Easily extended to accomodate three, four, or more alternate images.
<div id="image1">
<img ... >
<button ...>
</div>
<div id="image2" style="display: none">
<img ... >
<button ...>
</div>
That is, put the first image, and a button, inside a "< div >" element, and a second image, and a button inside a second "< div >" element that's initially hidden.
Then, each button's javascript simply needs to set its own div's CSS style to "display: none", and remove this style from the other div element, effectively hiding one image, and displaying the other one.
This approach also makes it possible to update the button's text or label, accordingly. If both buttons have the same label, the only apparent result is the image change.
Try this script block instead:
<script>
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg']
function changeImage() {
var img = document.getElementById( 'image' )
var url = images.shift() // remove first url from list
image.src = url // use it
images.push( url ) // append url to the end of the list
}
</script>
What you could do is declare an array which contains all your image urls:
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
Then when clicking the button, you remove the first image url from the the array by using shift and assign that to variable imageUrl.
Then you set that imageUrl to the src attribute of the image element on your page.
Then you add that imageUrl at the end of the array using push.
This will rotate the images in the imageUrls array on every click.
<html>
<head>
<title>How To Insert an Image</title>
<script>
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
You were very close! You just made mistake to assign a value to image.src instead of img.src. have a look at the code below :)
Using clicks:
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}
</script>
</head>
<body>
<img id="image" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" height="100px" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
Automatic image slider
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
setInterval(function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}, 5000)
</script>
</head>
<body>
<img id="image" src="image1.jpg" height="100px" />
</body>
</html>

Assign img' src dynamically

The page will display an image's url text correctly. But I am not sure how to assign the message to the img 's src to display the image.
<DIV class="msgStyle1" id="message">Waiting for image</DIV>
<div class="imgStyle1" id="message">
<img src=whatneedtogohere /></div>
function displayText(text) {
console.log(text);
document.getElementById("message").innerHTML=text;
window.castReceiverManager.setApplicationState(text);
};
Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:
<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
<img src="" id="image" />
</div>
JS:
document.getElementById('image').src = 'http://yourImagePathHere';
See it work here: http://jsfiddle.net/N3rCm/
First off, you shouldn't have multiple Id's on the page, it'll mess with your JS.
Next I would give your image a class if you can
//jquery example of what you would do
var imgSrc = 'http://wherever/youre/getting/this/from';
$('.myimageclass').attr('src', imgSrc);
//non jquery
var myImg = document.getElementsByClassName('myimageclass')[0]; //assuming it's the first one
//or if you can uniquely identify it
var myImg = document.getElementById('imgId');
myImg.src = imgSrc;

Categories

Resources