Swap multiple images from javascript array - javascript

I am coding a website with multiple pages of thumbnail image galleries. I want to populate the thumbnail images on each page from an array, so that I won't have to change the path of multiple images on each page. The folder path is defined in a var statement - which I would like to be the only unique element on each gallery page - and the images in each gallery's folder will have the same names (t1.jpg, t2.jpg, etc.).
I have the main image swap working, and tried to use a similar function for the thumbnails, but it doesn't work because the image ID is the same for all the thumbnail images. I could give each image a unique ID, but then would have to call a separate function for each thumbnail swap (15 per page).
I am a javascript novice and despite much searching I can't figure out how to work around this or find any similar examples. Any help or advice would be appreciated.
Javascript:
<script language="JavaScript" type="text/javascript">
<!--
// Thumbnail Image Array
var imgThumbs = new Array (
"t1.jpg",
"t2.jpg",
"t3.jpg"
)
//Main Image Array
var imgArray = new Array (
"f1.jpg",
"f2.jpg",
"f3.jpg"
)
//Image Path
var imgPath = "images/portfolio/samples/";
function preloadImages() {
for(var i = 0; i < imgArray.length; i++) {
var tmpImg = new Image;
tmpImg.src = imgPath + imgArray[i];
}
}
//Thumbnail Image Swap Function
function loadThumb(thumbID) {
var theThumb = document.getElementById('theThumb');
var newThumb;
newThumb = imgThumbs[thumbID];
theThumb.src = imgPath + newThumb;
}
//Main Image Swap Function
function swapImage(imgID) {
var theImage = document.getElementById('theImage');
var newImg;
newImg = imgArray[imgID];
theImage.src = imgPath + newImg;
}
//-->
</script>
HTML:
<div id="portfolio">
<div id="thumbnails">
<img src="images/portfolio/noThumb.jpg" id="theThumb" onload="loadThumb(0)" alt="Architect Portfolio Thumbnail 1" width="75" height="75" />
<img src="images/portfolio/noThumb.jpg" id="theThumb" onload="loadThumb(1)" alt="Architect Portfolio Thumbnail 2" width="75" height="75" />
<img src="images/portfolio/noThumb.jpg" id="theThumb" onload="loadThumb(2)" alt="Architect Portfolio Thumbnail 3" width="75" height="75" />
</div>
<div id="mainImage"><img src="images/portfolio/samples/f1.jpg" alt="Architecture Portfolio Main Image" id="theImage" /></div>
</div>

Each ID attribute on the page should be unique. Remove them and rewrite your code as:
function loadThumb(thumbID, obj) {
var newThumb = imgThumbs[thumbID];
obj.src = imgPath + newThumb;
}
And the corresponding HTML part will look like
<img src="images/portfolio/noThumb.jpg" onload="loadThumb(0, this)"
alt="Architect Portfolio Thumbnail" width="75" height="75" />
ps: Actually I do not see the purpose of that script - onload function could be triggered before the image is loaded in a preloadImages() function.
pps: try this code http://jsfiddle.net/4cKvs/ and jQuery variant http://jsfiddle.net/zSBNR/

If you are a Javascript novice I recommend you to search in google about
jQuery it is can help you a lot (Google also using it).

Related

Saving the original image before mouseover

I am trying to realize JavaScript that would change image on mouseover and revert it back, when mouseout. I have this code for that:
var list = document.querySelectorAll('span[data-oe-id] img');
var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
imgsrc[i] = list[i].src;
console.log(imgsrc[i]);
list[i].addEventListener("mouseover",function(event){event.target.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";},false);
list[i].addEventListener("mouseout",function(event){event.target.src=imgsrc[i];},false);
}
It is changing image on mouseover perfectly fine, but on mouseout, image is changed to undefined. For example:
<img src="undefined" class="img img-fluid" alt="A4Tech Bloody V8M">
Is result after mouseout
Src attribute cannot be set using event argument. you can use this keywords to access same selected element.
View Output in full screen
var list = document.querySelectorAll('img');
var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
imgsrc[i] = list[i].src;
list[i].addEventListener("mouseover",function()
{
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
list[i].addEventListener("mouseout",function()
{
this.src=imgsrc[i];
});
}
<img id="1" src="1" alt="img1"/>
<img id="2" src="2" alt="img2"/>
<img id="3" src="3" alt="img3"/>

how to load images after everything else is loaded?

i got some idea that to load a fake image on a div before original image finishies loading and that to be after winodws load.i got some code but cant understand in which part i have to put src image for fake image and original image.do help me out in this code .
my html part is
<div class="myimage"><img src="myimage.jpg" /></div>
note:Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading........
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});
You can use data attribute to do it:
<div class="myimage"><img data-orig="original.jpg" src="fake.jpg" /></div>
$(window).load(function(){
$('.myimage img').attr("src", $(this).data('orig')).removeAttr('data-orig');
});
You can add your images url to a custom data-url attribute and make your image url a base64 1x1 gif. And then when the page loads completely you can get your url from it. Basically it will be like this.
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="original-image.png" />
$(window).load(function() {
$("img").each(function() {
$(this).attr("src", $(this).attr("data-src"));
});
});

Javascript gallery with prev/next function AND thumbnail... nothing else

Short of going for something like Galleriffic
and modifying, hiding and removing elements, what would be a way to add a function by which thumbnails can also be clicked to display the image?
Much obliged to anyone who can point me in the right direction. I'm using the following by Paul McFedries at mcfedries.com.
<script type="text/javascript">
<!--
// Use the following variable to specify
// the number of images
var NumberOfImages = 3
var img = new Array(NumberOfImages)
// Use the following variables to specify the image names:
img[0] = "yellow1.jpg"
img[1] = "blue2.jpg"
img[2] = "green3.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
in the html:
<div class="galleryarrows">
<A HREF="javascript:PreviousImage()">
<IMG SRC="previous.png" BORDER=0></A>
<A HREF="javascript:NextImage()">
<IMG SRC="next.png" BORDER=0></A>
</div>
A quick, basic solution: Save the full size versions of your images in a folder called say, 'full_images', with the same names as the thumbnails.
Add an onClick event into the element img elements that display your thumbnails in the html, so they look something like this.
<img src = "yellow1.jpg" name = "thumb[0]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(0);" alt = "yellow"/>
<img src = "blue2.jpg" name = "thumb[1]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(1);" alt = "blue"/>
<img src = "green3.jpg" name = "thumb[2]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(2);" alt = "green"/>
In your javascript, add this function
function DisplayImage(id){
imgNumber = id;
document.images["VCRImage"].src = "full_images/" + img[id];
}
This will display in an element with the name 'VCRImage'.
Not my favourite solution this, but quick, and should work. If Javascript is new to you, then you might as well check out jQuery. It's a lot easier to use, and is way more cross-browser compatible.

Javascript image load and display

I have a web page that shows an image and two arrows, with Javascript.
When the right arrow is clicked, the index increments and a new image should be loaded.
When the left arrow is clicked, the index decrements and a new image should be loaded.
I added some alerts to the code which shows that the index is incremented, but the new image is still not displayed. I would appreciate pointers on what's wrong with the code.
Only the initial image is always shown and it's not updated. The link change colors and the alerts are displayed.
<html>
<head>
<title> Gallery</title>
</head>
<script type="text/javascript">
var rightTarget;
var leftTarget;
var index = 516;
function rightLinkClicked(e) {
rightTarget = e.target;
rightTarget.style.color = "green";
leftTarget.style.color = "black";
index = index +1;
alert ("right1")
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG";
alert ("right2 - index = IMG_0" + index + ".JPG")
}
function leftLinkClicked(e) {
leftTarget = e.target;
leftTarget.style.color = "red";
rightTarget.style.color = "black";
if (index >516) {
index = index -1;
}
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG"
alert ("left - index = "+ index)
}
function addListeners() {
var rightLink = document.getElementById("rightlinkid");
rightLink.addEventListener('click', rightLinkClicked, false);
var leftLink = document.getElementById("leftlinkid");
leftLink.addEventListener('click', leftLinkClicked, false);
}
window.addEventListener('load', addListeners, false);
</script>
</head>
<body>
<a id="leftlinkid">Left Link
<img src="icons/left.gif"; alt="left arrow" title="">
</a>
<div id="myimg">
<img id="img" src="pics/IMG_0516.JPG"; alt="start arrow" title="" width="640" height="480">
</div>
<a id="rightlinkid">Right Link
<img src="icons/right.gif"; alt="right arrow" title="">
</a>
</body>
</html>
You are using getElementsByTagName which returns a collection of DOM elements, which is not the same as your single image. You should do
img = getElementById('img');
The code img=document.getElementsByTagName('img'); returns a collection. You need to specify which images' source you want to modify, like img[index + 1].src = .... I think you will want to use index + 1 so that it doesn't start counting with the first image (the left arrow). A better solution might be to give all of your images the same class name and find by class (document.getElementsByClassName('myClass');).

Problem with degradable JavaScript slideshow

UPDATE: I've edited the code below to show what I was using when I tried to work with CSS visibility. I'm still stuck with this problem. I've also tried to remove the preloader() function from the body onLoad, but I can't use getElementById because the element hasn't loaded. My final thought was to just call rand(5) from within the HTML itself so that it adds a number to the end of the image filename if Javascript is enabled, but I'm not even sure how to incorporate that directly into the HTML. Any help would be greatly appreciated!
I created a slideshow with Javascript. The HTML calls a static image to display in the event Javascript is not enabled in the browser. If Javascript is enabled in the browser, it is supposed to load a random image in the place of the static image.
The problem I'm encountering is when Javascript is enabled, you see the static image load with the page and then, if the random image is different, you see it quickly load right after that. So it looks like two images cycling quickly on page load.
Here is the Javascript code I'm using:
// Define images used in slideshow
imgArray = new Array(
"header_img1.jpg",
"header_img2.jpg",
"header_img3.jpg",
"header_img4.jpg",
"header_img5.jpg"
);
baseURL = "images/";
// Preload slideshow images
function preloader() {
domElement = document.getElementById('gallery-image');
domElement.style.visibility = "hidden";
// counter
var i = 0;
// create object
imageObj = new Image();
// start preloading imgArray
for (i=0; i<3; i++) {
imageObj.src=imgArray[i];
}
}
// Select random image to display for slideshow
function random_img() {
domElement.style.visibility = "visible";
rand = Math.round(Math.random()*(imgArray.length - 1));
document["faces"].src = baseURL + imgArray[rand];
rand += 1;
}
Here is the accompanying HTML:
<body onLoad="preloader();random_img();">
.
.
.
<a href="#" onclick="f_slideshow(-1);return false;">
<img src="images/header_img1.png" alt="" width="26" height="207" /></a>
<img src="images/header_img1.jpg" alt="" width="529" height="197" class="img-1" name="faces" />
<a href="#" onclick="f_slideshow(1);return false;">
<img src="images/header_img2.png" alt="" width="27" height="207" /></a>
How do I change what I have so when Javascript is enabled, you don't see the two cycling images?
In your preLoader() manipulate the style to hide the elements you wish to hide if javascript is enabled.
This way, if it is enabled the elements will hide, if it is not, the clearly the javascript to hide them will not run.
example
var domElement = document.getElementById('id-of-element');
domElement.style.display = 'none';
This is the JavaScript code that solved my problem:
// Define images used in slideshow
imgArray = new Array(
"header_img1.jpg",
"header_img2.jpg",
"header_img3.jpg",
"header_img4.jpg",
"header_img5.jpg"
);
baseURL = "images/";
// Hide static image and preload slideshow images
function preloader() {
// counter
var i = 0;
// create object
imageObj = new Image();
// start preloading imgArray
for (i=0; i<3; i++) {
imageObj.src=imgArray[i];
}
}
// Control previous/next functions of slideshow
numImages = imgArray.length;
function f_slideshow( xflip ) {
// grab source of current image
var curImage = document["faces"].src;
// get image number from string and convert to int
curImage = parseInt(curImage.substring(curImage.length-5, curImage.length));
// create source for next/previous link
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document["faces"].src = baseURL + imgArray[curImage - 1];
}

Categories

Resources