Multiple instances of random image rotation - javascript

I am struggling to work out how to make all instances of images with the id="cover__thumb" rotate randomly through the predefined images.
Currently only the first id="cover__thumbs" will rotate, it has no affect on the other images with the same id.
There won't always be 4 images, sometimes more sometimes less. Is there a solution that works for any image with the this id?
Fiddle
https://jsfiddle.net/bpLdkhg0/
JS
function rotateImages()
{
var thumbImages = new Array( );
thumbImages[0] = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg";
thumbImages[1] = "http://cdn.images.express.co.uk/img/dynamic/13/590x/magnolia-tree-630524.jpg";
thumbImages[2] = "http://cdn.images.express.co.uk/img/dynamic/109/590x/Oak-tree-580618.jpg";
var image = document.getElementById('thumb__cover');
var randomImageIndex = Math.floor( Math.random( ) * thumbImages.length );
image.src = thumbImages[randomImageIndex];
}
window.setInterval(rotateImages, 1000);
HTML
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">

Use the class attribute if you want to select multiple DOM elements at once:
HTML:
<img class="thumb__cover" ... />
JS:
var images = document.querySelectorAll(".thumb__cover");
or
var images = document.getElementsByClassName("thumb__cover");
Now, images is a nodeList that can have any number of elements. To set the src attribute for each of them, you'll have to loop through the items in the list:
for (var i = 0; i < images.length; i += 1) {
var image = images[i];
var randomImageIndex = Math.floor(Math.random() * thumbImages.length);
image.src = thumbImages[randomImageIndex];
}
More about node lists: https://developer.mozilla.org/en/docs/Web/API/NodeList

Related

Display Random images using a foreach loop and and one < img > tag

I have set of Images. I want to display images Randomly. Inside for-each loop I'm calling images. Suppose I have 10 records and therefore 10 images should be display randomly from given set of images in side the script. But the problem is only a one image will display and rest of images wont visible. loop working fine. Is getElementById can use for one id only once?? please I need a help to solve this matter and where I made wrong.
This is the code.
<script>
var myPix = new Array("/Contents/img/CarrerGuide/office-1.png",
"/Contents/img/CarrerGuide/office-2.png",
"/Contents/img/CarrerGuide/office-3.png",
"/Contents/img/CarrerGuide/office-4.png",
"/Contents/img/CarrerGuide/office-5.png",
"/Contents/img/CarrerGuide/office-6.png",
"/Contents/img/CarrerGuide/office-7.png",
"/Contents/img/CarrerGuide/office-8.png",
"/Contents/img/CarrerGuide/office-9.png",
"/Contents/img/CarrerGuide/office-10.png");
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
</script>
#{ var counter = 1; }
<tr>
#foreach (var item in Model)
{
<td>
<img id="myPicture" name="myPicture" alt="some image" class="img-responsive">
item.jobPosition
</td>
if (counter % 3 == 0) //Display 3 courses at a row
{
#:</tr><tr>
}
counter++;
}
You will have to select all the elements having attribute names as $('[name=\'myPicture\']') and iterate them to change src of each element. In your example, you are not getting randomNum for each element.
Also note that you should not have same iss for multiple elements in same document!
var myPix = ["/Contents/img/CarrerGuide/office-1.png",
"/Contents/img/CarrerGuide/office-2.png",
"/Contents/img/CarrerGuide/office-3.png",
"/Contents/img/CarrerGuide/office-4.png",
"/Contents/img/CarrerGuide/office-5.png",
"/Contents/img/CarrerGuide/office-6.png",
"/Contents/img/CarrerGuide/office-7.png",
"/Contents/img/CarrerGuide/office-8.png",
"/Contents/img/CarrerGuide/office-9.png",
"/Contents/img/CarrerGuide/office-10.png"
];
$('[name=\'myPicture\']').each(function() {
var randomNum = Math.floor(Math.random() * myPix.length);
this.src = myPix[randomNum];
});

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');

Use javascript selectors without jQuery to select images

I have some images like this:
<img src="http://127.0.0.1/test/images/cat01.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat02.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat03.png" alt="00" class="cat_img">
and I want to select the image names (cat01.png, cat03.png and cat03.png) with javascript (without jQuery).
How can I do that ?
I have tried :
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
console.log('Images '+images);
Thanks for help.
Or like this (no need to use Array.prototype.slice)
var images = Array.prototype.map.call(
document.querySelectorAll(".cat_img"),
function(img) {
var src = img.src,
lastIndex = src.lastIndexOf('/');
return src.slice(lastIndex + 1);
});
You can loop over your images array using map and return the part of the src attribute that you want (everything after the last /):
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
var imageNames = images.map(function( image ) {
return image.src.substring( image.src.lastIndexOf("/") + 1 );
} );
console.log(imageNames);
jsfiddle
Here is a simple example using regex with a loop.
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
for(i = 0; i < images.length; i++) {
console.log(images[i].src.replace(/.+\//, ''));
}
jsfiddle
So to build your array of names, just replace the console.log(...) line with images[i] = images[i].src.replace(/.+\//, '')

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.

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