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

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.

Related

Generate array of image in javascript inside <div>

I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header.
This is the div
<div style="min-height:1000px;position:relative;" id="home">
below of the div is containing the logo, menu and nav part.
<div class="container">
<div class="fixed-header">
<!--logo-->
<div class="logo" >
<a href="index.html">
<img src="images/logo.png" alt="logo mazmida" height="142" width="242">
</a>
</div>
<!--//logo-->
This is the javascript
<script>
var imgArray = [
'images/1.jpg',
'images/2.jpg',
'images/3.jpg'],
curIndex = 0;
imgDuration = 2000;
function slideShow() {
document.getElementID('home').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
You have a few issues with your script. I've made a live JSbin example here:
https://jsbin.com/welifusomi/edit?html,output
<script>
var imgArray = [
'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/220px-Homer_Simpson_2006.png',
'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png',
'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png'
];
var curIndex = 0;
var imgDuration = 1000;
var el = document.getElementById('home');
function slideShow() {
el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')';
curIndex++;
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
There are a few issues with your script:
On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at https://developer.mozilla.org/en-US/docs/Web/CSS/background for other attributes to related to background image CSS
Also it's document.getElementById
Optimizations
And you can use mod % trick to avoid zero reset
Use setInterval instead of setTimeout
Further optimzations
Use requestAnimationFrame instead of setTimeout/setInterval
I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face.
document.getElementID('home').src = imgArray[curIndex]
You are targeting a div with an ID of home, but this is not an Image element (ie ,
But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour).
I hope this helps.
You are trying to change the src property of a div, but divs do not have such property.
Try this:
document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')"
This changes the style of the target div, more precisely the image to be used as background.
As you want to change the background image of the div, instead of document.getElementID('home').src = imgArray[curIndex] use
document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";
in JavaScript or
$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")'); in jquery.
To achieve expected result, use below option of using setInterval
Please correct below syntax errors
document.getElementID to document.getElementById
.src attribute is not available on div tags
Create img element and add src to it
Finally use setInterval instead of setTimeout outside slideShow function
var imgArray = [
'http://www.w3schools.com/w3css/img_avatar3.png',
'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300',
'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'],
curIndex = 0;
imgDuration = 2000;
var home = document.getElementById('home')
var image = document.createElement('img')
function slideShow() {
if(curIndex != imgArray.length-1) {
image.src = imgArray[curIndex];
home.appendChild(image)
curIndex++;
}else{
curIndex = 0;
}
}
setInterval(slideShow,2000)
<div style="position:relative;" id="home"></div>
code sample - https://codepen.io/nagasai/pen/JLKvME

Generate html using Javascript

I have a gallery page that is updated often with new images. I use simple HTML to post the photos. My process currently is copy and paste the set of tags for a photo and change the number to correspond with the image file name. E.G. I change the number 047 to 048. Copy-Paste, change it to 049. This goes on until I have reached the number of additional photos. As you can see, this is very inefficient and there must be a better way of doing this. I was wondering if there is a simpler way to achieve this with Javascript? Perhaps generate additional tags by inputing a certain number or range?
Any ideas that would make this process efficient are welcomed please! Thank you!
<div class="cbp-item trim">
<a href="../assets/images/trim/img-trim-047.jpg" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="../assets/images/trim/img-trim-047.jpg" alt="">
</div>
</a>
</div>
You could use a templating solution. There are several libraries for that, but you can also implement it yourself.
Here is one way to do that:
Put the HTML for one image in a script tag that has a non-standard language property so the browser will just ignore it
Put some keywords in there that you'll want to replace, e.g. {url}. You can invent your own syntax.
Read that template into a variable
In the JS code, put all the images' URLs in an array of strings
For each element in that array, replace the keywords in the template string with that particular URL, and concatenate all these resulting HTML snippets.
Inject the resulting HTML into the appropriate place in the document.
Here is a snippet doing that:
// Add new images here:
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/330px-SNice.svg.png",
"https://nettemarie357.files.wordpress.com/2014/09/smiley-face.jpg?w=74&h=74",
];
// Load the template HTML
var template = document.querySelector('script[language="text/template"]').innerHTML;
// Use template to insert all the images:
container.innerHTML = images.map(url => template.replace(/{url}/g, url)).join('');
img { max-width: 50px }
<div id="container"></div>
<script language="text/template">
<div class="cbp-item trim">
<a href="{url}" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="{url}" alt="">
</div>
</a>
</div>
</script>
This would help you creating it programatically:
var new_row = document.createElement('div');
new_row.className = "cbp-item trim";
var a = document.createElement('a');
a.href = "../assets/images/trim/img-trim-047.jpg";
a.className= "cbp-caption cbp-lightbox";
document.body.appendChild(a);
var div = document.createElement('div');
div.className = "cbp-caption-defaultWrap";
var img = document.createElement('img');
img.src= "../assets/images/trim/img-trim-047.jpg";
div.appendChild(img);
a.appendChild(div);
new_row.appendChild(a);
If it is just about printing HTML, I suggest you to use plugins like Emmet for Sublime Text editor.
When you install this plugin and see how it works, you can simple create a complex html in a way that 'for' loop would do this. This will help you to change only the image/link number of every item.
Check the demo in the link, that I added.
Here's an example in Java Script that will generate the html you will need. Set the total to whatever number you need to generate the number of images you want.
var total = 47;
var hook = document.getElementById('hook');
// Main Node for SlideShow
var node = document.createElement('div');
node.classList = "cbp-item trim";
// Work out the correct number
var n = function(int) {
var length = int.toString().length;
return length === 1
? '00' + int
: length === 2
? '0' + int
: length
}
// Create the item
var createItem = function(int){
// Create Anchor
var a = document.createElement('a');
a.href = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg" class="cbp-caption cbp-lightbox';
a.classList = 'cbp-caption cbp-lightbox';
// Create Div
var div = document.createElement('div');
div.classList = 'cbp-caption-defaultWrap';
// Create Image
var img = document.createElement('img');
img.src = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg';
img.alt = 'gallery image';
// Finalise Dom Node
var container = div.appendChild(img)
a.appendChild(div);
// Return Final Item
return a
}
// Create Items
for (var i = 1; i < total + 1; i++) {
node.appendChild(createItem(i));
}
// Append Main Node to Hook
hook.appendChild(node);
<div id="hook"></div>

how to change src value using javascript

<div id="3" class="dsi" onmousedown="test(3);" ondrop="checkImg('3');dropIt(event,3);" ondragover="event.preventDefault();">
<img src="1.gif" draggable="true" ondragstart="dragIt(event,4);" id="pic4" />
I want to change src value using javascript. There are nine dives and they already have 1 to 9 gif images. How can I add new src values leaving the rest of the things unchanged? (I mean draggable="true" ondragstart="dragIt(event,4);" id="pic4")
function ft1() {
var imgSrcs = ['2.gif', '1.gif', '3.gif', '4.gif', '5.gif', '6.gif', '7.gif', '8.gif'];
var myImages = [];
for (var i = 0 ;i <=((imgSrcs.length)-1);i++) {
var v = i;
var img = new Image();
img.src = imgSrcs[i];
var div0 = document.getElementById(v+1);
div0.appendChild(img);
myImages[v+1] = img;
}
Using this I can replace div images. But how can I remove first assigned src value and then replace new images?
As stated here, simply do:
document.getElementById("pic4").src="...";
Try this.
$('.img').attr('src','http://source');

modify the end of an image source from 's.jpg' to 'o.jpg' with javascript

My CMS has a plugin for pulling in facebook images with stories. I cannot change it.
In the source it creates the image URL ends in s.jpg but I would like to modify it so it ends in o.jpg in order to pull in the largest photo type
This is the code:
<div class="post_picture">
<img src="http://photos-g.ak.fbcdn.net/hphotos-ak-ash3/534627_477964682254266_1412043521_s.jpg" alt="">
</div>
Is this possible? I would image you copy the source URL, modify the end from s.jpg to o.jpg and the replace the old URL w/ the new one.
EDIT:
Thanks everyone for your replies & solutions, below is another solution I found...
$('.div1>img').attr('src',function(i,e){
return e.replace("s.jpg","o.jpg");
})
ex - http://jsfiddle.net/designaroni/4Da2a/
function imgSrcOverwrite() {
var imgs = document.getElementsByTagName('img'),
loopImg, fbImgs = [];
// Loop through each IMG, check if it's a facebook image &
// then replace _s.jpg with _o.jpg in the src attribute
for ( var x=0; x<imgs.length; x++ ) {
loopImg = imgs[x];
if ( loopImg.src.indexOf('photos-g.ak.fbcdn.net') > -1 ) {
loopImg.src = loopImg.src.replace('_s.jpg', '_o.jpg');
fbImgs.push(loopImg);
}
}
imgs = loopImg = null;
// return array of fb images so you can do more stuff with them
return fbImgs;
}
imgSrcOverwrite();
If you're using jQuery I'd replace the second line with
var imgs = $('.post_picture img'),
http://jsfiddle.net/CoryDanielson/jmzk2/
Here's a quick example of how it may be possible.
// get image dom element
var img = document.getElementById('imageId');
// update src
img.src = img.src.replace(/s.jpg/, 'o.jpg');
If you are using jquery,
Try to access the img tag by this -
var src = '';
$('.post_picture').find('img').each(function(){
src = $(this).attr('src').toString().replace('_s.jpg', '_o.jpg');
$(this).attr('src',src);
});

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