Javascript image array [duplicate] - javascript

This question already has answers here:
How to add a list of images to the document from an array of URLs?
(2 answers)
Closed 7 years ago.
needing some help. I have two divs that I need to fill with images. The images can't be random as div 1's image needs to correspond to div 2's. I've been playing around and have managed to get the javascript working to this point. The problem is I need the script to write to the div backgrounds rather than fill the div with an image.
<script>
var random = Math.random();
function random_imglink(arr){
var ry = Math.floor(random*arr.length);
document.write(
'<img src="'+arr[ry]+'" border=0 class="two">'
);
}
var myimages = [
"img1.jpg", "img2.jpg","img3.jpg"
],
myimagesA = [
"img1b.jpg","img2b.jpg","img3b.jpg"];
</script>
<div><script>random_imglink(myimages);</script> </div>
<DIV><script>random_imglink(myimagesA);</script></div>

Your code needed quite an overhaul. This is what it should look like after being fixed:
<div id='a'>A</div>
<div id='b'>B</div>​
<script>
var random = Math.random();
function random_imglink(arr, id){
var ry = Math.floor(random*arr.length);
document.getElementById(id).style.backgroundImage = "url('" + arr[ry] + "')";
}
var myimages = [
"http://img1.jpg.to"],
myimagesA = ["http://img1b.jpg.to"];
random_imglink(myimages, 'a');
random_imglink(myimages, 'b');
</script>
Demo

To set an image as the background of an element you can use this:
document.getElementById("myDivId").style.backgroundImage = "url(/path/to/img)";
In your code, you could do it something like:
var random = Math.random();
function random_imglink(divId, arr){
var ry = Math.floor(random*arr.length);
document.getElementById(divId).style.backgroundImage = "url(" + arr[ry] + ")";
}
var myimages = ["img1.jpg", "img2.jpg","img3.jpg"],
myimagesA = ["img1b.jpg","img2b.jpg","img3b.jpg"];
random_imglink("firstDiv", myimages);
random_imglink("secondDiv", myimagesA);
html:
<div id="firstDiv"></div>
<div id="secondDiv"></div>

Smallest possible change of the current code; make the function write a div tag with a style attribute instead of an image tag:
document.write('<div style="background:url('+arr[ry]+')">');
Put the script where you want the start tag:
<script>random_imglink(myimages);</script> </div>

Related

How to make a picture change randomly in a website?

I want to make a website that the user will decide something. The user will click what he or she chose.
I want to know how to make the picture change to a random other picture everytime the user clicks it.
Is there any way to do that?
create an array with all the urls of the images you wanna use.
e.g.
HTML:
<img id='the-image-to-change'/>
JS:
var imageUrls = [
'http://placehold.it/255x255&text=A',
'http://placehold.it/255x255&text=B',
// ... more
'http://placehold.it/255x255&text=Z'
];
if you're not using jQuery:
var img = document.getElementById('the-image-to-change');
img.addEventListener("click", function() {
this.src = imageUrls[Math.floor(Math.random() * imageUrls.length)];
});
if jQuery (has not been tested)
img = $('#the-image-to-change');
img.on('click', function() {
this.src = imageUrls[Math.floor(Math.random() * imageUrls.length)];
});
This should give you the type of effect you want. Basically you're storing your images in an array, then you're going to randomly pick an index, then display it.
var yourImages = ["image1.png","image2.png","image3.png"];
var randomImage = Math.round(Math.random()*yourImages.length);
function displayImage()
{
document.write(yourImages[randomImage]);
}
Here is an example that's more geared toward what you asked, after I read your question again. If the user clicks on the image, it'll change to a random one.
JS:
<img id="currentImage" src="defaultImage.png" onclick="changePicture()">
<script>
function changePicture(){
var yourImages = ["image1.png","image2.png","image3.png"];
var randomImage = Math.round(Math.random()*yourImages.length);
var setImg = document.getElementById("currentImage").src;
setImg = yourImages[randomImage];
}
</script>
jQuery:
<img id="currentImage" src="defaultImage.png">
<script>
$("#currentImage").click(function(){
var yourImages = ["image1.png","image2.png","image3.png"];
var randomImage = Math.round(Math.random()*yourImages.length);
$("#currentImage").attr("src", yourImages[randomImage]);
});
</script>
Create an array of your picture, and use
Math.random();
To select a random index from your picture array that will be shown??

How to add the background css into this jQuery? [duplicate]

This question already has an answer here:
How to change the css attribute of #header using jQuery and an array of images?
(1 answer)
Closed 8 years ago.
As you can see in my fiddle here, http://jsfiddle.net/HsKpq/460/ I am trying to show the images into the
$('#header').css('background-image',..................).fadeTo('slow',1);
How can I do this?
var img = 0;
var imgs = [
'http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg',
'http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg',
'http://www.istockphoto.com/file_thumbview_approve/9712604/2/istockphoto_9712604-spring-sunset.jpg'
];
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});
// populate the image with first entry
$('img').attr('src',imgs[0]);
var opacity = 0.1; // change this for minimum opacity
function changeBg() {
$('img').fadeTo('slow',opacity,function(){
$('#header').css('background-image',..................).fadeTo('slow',1);
});
}
setInterval(changeBg,5000);
You can do it without img elements, using backgound css property, like here:
var img = 0;
var imgs = [
'http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg',
'http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg',
'http://www.istockphoto.com/file_thumbview_approve/9712604/2/istockphoto_9712604-spring-sunset.jpg'
];
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});
var img = imgs[0];
var opacity = 0.1; // change this for minimum opacity
function changeBg() {
$('#header').fadeTo('slow',opacity,function(){
$('#header').css('background-image', 'url(' + img + ')').fadeTo('slow',1);
});
}
setInterval(changeBg,5000);
Don't know what you were trying to do with the background image and then populating the first image to a non-existent element.
Here is an updated fiddle: http://jsfiddle.net/HsKpq/464/
But this may be what you are looking for to show the images :
var $h_image = $('#headerImage');
function changeBg() {
$h_image.fadeTo('slow',opacity,function(){
$h_image.attr('src', imgs[Math.floor((Math.random() * 3))]).fadeTo('slow',1);
});
}
You also need to change your HTML to this :
<div id="header"><img id="headerImage"/></div>

Simple JavaScript image rotator

I have a simple image rotator on a website consisting of 4 images that have to appear for a few seconds before showing the next one. It seems to work on its first cycle but then when it gets back to the first image it doesn't show that one but works again from the second image and so on always missing that image on every cycle.
The function is called using onLoad EH in the body. In the body there is an img with my first image inside it. I'm a noob so please be gentle if I've missed anything out.
Here's what I have...
<body onLoad="sunSlideShow()">
<img src="IMAGES/slider1.gif" alt="slide-show" id="mySlider" width="900">
<body>
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0
function sunSlideShow()
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
i = 1;
setTimeout("sunSlideShow()", 3000);
}
sunSlideShow()
Change it to this:
else
i = 0;
setTimeout("sunSlideShow()", 3000);
Further to my other answer (which was wrong!)... Try this:
http://jsfiddle.net/pq6Gm/13/
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(sunSlideShow,3000);
});
var quotes = [
"http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2007/07/11/sun128.jpg",
"http://icons.iconarchive.com/icons/robinweatherall/seasonal/128/sun-icon.png",
"http://www.astronomytoday.com/images/sun3.gif",
"http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png"
];
var i = 0;
function sunSlideShow() {
document.getElementById("mySlider").src = quotes[i];
if (i < (quotes.length-1))
{
i++;
}
else
{
i = 0;
}
}
</script>
<body>
<img src="http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png" id="mySlider"/>
</body>
==================================================================
EDIT: This is wrong... please find my other answer on this page.
==================================================================
To start with, I wouldn't use ... you're better off starting the script with jquery once the page is loaded.
Add this to your head section:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
</script>
That will fire the sunSlideShow function once the page is loaded.
Then, you're starting your slideshow with var i = 0... but when you've got to the fourth image, you're setting it to 1?
I would be tempted to use a while loop to achieve what you want.
Something like this:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0;
function sunSlideShow(){
while (i<4)
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
{
i = 0;
}
sleep(3000);
}
}
function sleep(miliseconds){
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()){}
}
</script>
This script hasn't been tested... but it should start the sunSlideShow function once the page has loaded and then change the image every 3 seconds.
I too searched the web trying to find a general solution to the problem of rotating an image about its center. I came up with my own solution which works perfectly. The basic concept is simple: rotate the entire context by the desired angle (here called 'tilt'); calculate the image's coordinates in the NEW coordinate system; draw the image; lastly, rotate the context back to its original position. Here's the code:
var xp = rocketX * Math.cos(tilt) - rocketY * Math.sin(tilt);
var yp = rocketX * Math.sin(tilt) + rocketY * Math.cos(tilt);
var a = rocketX - xp;
var c = Math.sqrt(a*a + (rocketY-yp)*(rocketY-yp));
var beta = Math.acos(a/c);
var ap = c * Math.cos(tilt + beta);
var bp = c * Math.sin(tilt + beta);
var newX = rocketX + ap;
var newY = rocketY - bp;
context.rotate(tilt);
context.drawImage(littleRocketImage, newX-9, newY-40);
context.rotate(-tilt);
In the penultimate line, the constants '9' and '40' are half the size of the image; this insures that the rotated image is placed such that its center coincides with the center of the original image.
One warning: I use this only for first quadrant rotations; you'll have to put in the standard tests for the other quadrants that change the signs of the components.
Update: 2021
You can use the light-weight library Ad-rotator.js to setup simple Ad-rotation like this -
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>
<script>
const instance = rotator(
document.getElementById('myelement'), // a DOM element
[ // array of ads
{ url: 'https://site1.com', img: 'https://example/picture1.jpg' },
{ url: 'https://site2.com', img: 'https://example/picture1/picture2.jpg'},
// ...
]
);
</script>
<body onLoad="instance.start()">
<div id="myelement"></div>
<body>
Reference Tutorial

Javascript random image generator in css-based page

as the title says I'm trying to figure out how to call this javascript function in my webpage. It's for my business, and the template is just a basic, free one. I'm sure for someone more experienced than me it's probably just a simple matter of formatting it correctly. Here's what I'm working with.
Code that goes in the HEAD portion of the webpage:
var theImages = new Array()
theImages[0] = 'splash1.jpg'
theImages[1] = 'splash2.jpg'
theImages[2] = 'splash3.jpg'
theImages[3] = 'splash4.jpg'
theImages[4] = 'splash5.jpg'
theImages[5] = 'splash6.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="'+theImages[whichImage]+'">');
}
</script>
Now to call the function I use:
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
Here's the page in which I'm trying to implement it:
http://coloradopp.com/index4.html
Instead of just displaying an image, I would like to call that function. Splash 1-6 are all the same size as the original image.
Here's the code snippet:
<div id="splash">
<img class="pic" src="images/splash1.jpg" width="870" height="374" alt="" />
</div>
As you can tell the page calls on a style sheet (style.css) for all the formatting.
Can anyone offer any tips on how to make this work? From what I've gathered, one cannot implement javascript into css sheets. Thanks in advance.
Do something like this:
showImage() {
var theImages = [ 'splash1.jpg', 'splash2.jpg', 'splash3.jpg', 'splash4.jpg', 'splash4.jpg' ];
var img = theImages[Math.round(Math.random() * (theImages.length - 1))];
document.getElementById('splash').innerHTML = '<img src="' + img + '">');
}
First move your javascript code inside the function something like:
function showImage(){ ...your code goes here...}
And then you can initiate the function on page load like this:
<body onload="showImage()">
You can set the images dynamically as background-image and place something like this
<script>
document.write('<style>#splash{ background-image:url(\'images/splash'+Math.round(Math.random()*5+1)+'.jpg\');}</style>');
</script>
at the head of your page. With this solution you have to set fix dimensions for your div tag (870x374)

Random Images two locations same set

So basically what I am looking for is how to have a random image javascript code but the images are in two different divs but I would like the random images to come from the same array.
I plan to take a JS class this summer so I don't have to ask anymore because I feel like this should be simple...
Currently I am just using the code from javascript kit in two different locations:
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="image1.gif"
myimages[2]="image2.gif"
myimages[3]="image3.gif"
myimages[4]="image4.gif"
myimages[5]="image5.gif"
myimages[6]="image6.gif"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>
but what I hope to achieve is:
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="image1.gif"
myimages2[1]="image1a.gif"
myimages[2]="image2.gif"
myimages2[2]="image2a.gif"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0) ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>
RENDERED CODE WITHIN DIVS
<div class="one"><img src="img1.gif"></div>
<div class="two"><img src="img1a.gif"></div>
REFRESHED
<div class="one"><img src="img2.gif"></div>
<div class="two"><img src="img2a.gif"></div>
Here's one particular approach.
I start out by identifying all of the variables I plan on using:
var rIndex1, rIndex2,
oContainer1, oContainer2,
aImages;
Now I assign initial references to DOM containers, as well as populate my images array:
oContainer1 = document.getElementById("left");
oContainer2 = document.getElementById("right");
aImages = ['http://placekitten.com/200/200','http://placekitten.com/201/201',
'http://placekitten.com/202/202','http://placekitten.com/203/203',
'http://placekitten.com/204/204','http://placekitten.com/205/205'];
Because I'll be generating random index values a few times, I create a simple function for this logic:
function rIndex ( iMax ) {
return Math.floor( Math.random() * iMax );
}
In order to see the effect over and over, I'm running the logic within an anonymous function, stored within an interval that runs every second. You, of course, could just wrap it up in a named function to be called once.
setInterval(function(){
Setting initial random values for my index variables.
rIndex1 = rIndex( aImages.length );
rIndex2 = rIndex( aImages.length );
We don't want both images to be the same, so as long as we have selected identical values, let's choose another index value for the second index.
while ( rIndex2 == rIndex1 ) rIndex2 = rIndex( aImages.length );
Lastly, I overwrite the innerHTML property of the containers with new image elements.
oContainer1.innerHTML = '<img src="%s" />'.replace( /%s/, aImages[ rIndex1 ] );
oContainer2.innerHTML = '<img src="%s" />'.replace( /%s/, aImages[ rIndex2 ] );
}, 1000);
Demo: http://jsbin.com/ubuxoj/edit#javascript,html
This could be improved upon a bit. For instance, it's possible that while aImages[2] is currently being shown in oContainer2, it may be reapplied the next time around. You could check to make sure you only select an image other than that which is currently being displayed in your container.
For what you are wanting to do, I don't see the point to store them on arrays and do complex stuff to get them.
If the URL paths are the same, there is no need to chose them from an array:
function refreshImages() {
var max = 10;
var rand = (Math.floor(Math.random() * max) + 1); //1-10
var src1 = "http://example.com/image" + rand + ".gif";
var src2 = "http://example.com/image" + rand + "a.gif";
document.getElementById("div1").innerHTML = "<img src='" + src1 + "' />";
document.getElementById("div2").innerHTML = "<img src='" + src2 + "' />";
}
window.onload = function() {//need to wait until the divs are loaded
refreshImages();
}​
and in your HTML:
<div id="div1"></div>
<div id="div2"></div>
Note: I added +1 to rand because in your example you started at image1, if you want the possibility to start at image0, just remove the +1 and the range of possibilities will change to 0-9
jsFiddle demo (because the images don't exist, you need to see the source code)
If your purpose is to be extensible (e.g., if you don't know how many images you will have), I would normally recommend appending to the DOM and creating the <div/> randomly as well, and also looping to create the divs so you don't need to create them manually. However, if this is not the case, by using the pattern you have used, you could do something like this:
<script>
var random = Math.random();
function random_imglink(arr){
var ry = Math.floor(random*arr.length);
document.write(
'<img src="'+arr[ry]+'" border=0>'
);
}
var myimages = [
"image1.gif", "image2.gif"
],
myimagesA = [
"image1a.gif", "image2a.gif"
];
</script>
<div class="one"><script>random_imglink(myimages);</script></div>
<div class="two"><script>random_imglink(myimagesA);</script></div>
We first make a random number which we reuse throughout the life of the script on this page load. Then we define the writing function and then make our 2 arrays available so they can be referenced by the function calls within the divs. It's hard to know exactly what you want without more detail, but hopefully this will give some ideas.

Categories