Random Images two locations same set - javascript

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.

Related

How to add while loop to randomizer

I am trying to learn JavaScript and have made a website which randomizes gifs onclick from an array.
What I would like to do now is insert a while loop so that it will compare the currentgif to the next randomized image so no duplicates are shown but I can't quite figure out what I am doing wrong, most likely a syntax issue.
HTML
<!DOCTYPE html>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/rand.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<head>
<title>Randomizer</title>
</head>
<body>
<p>This image is random</p>
<a href="#" class="click">
<section>
<img>
<script>
getRandomImage()
</script>
</img>
</section>
</a>
</body>
</html>
JavaScript
var randomImage = new Array();
randomImage[0] = "images/1.gif";
randomImage[1] = "images/2.gif";
randomImage[2] = "images/3.gif";
function getRandomImage() {
var number = Math.floor(Math.random()*randomImage.length);
document.write('<img src="'+randomImage[number]+'" />');
}
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomImage.length);
$(this).html('<img src="'+randomImage[number]+'" />');
});
});
You first need to get which image it is:
function returnImgNum(){
var imgNum = parseInt($('img').attr('src').split("/")[1].replace('.gif', ""));
return imgNum;
}
Then make a loopable function (or just make a while loop, I like doing it this way)
function placeRand(number){
if(number != returnImgNum()){
document.write('<img src="'+randomImage[number]+'" />');
} else {
placeRand(number){
}
}
Then add that comparator loop to your function:
function getRandomImage() {
var number = Math.floor(Math.random()*randomImage.length);
placeRand(number);
}
var random_images_array = ['smile.gif', 'frown.gif', 'grim.gif', 'bomb.gif'];
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
Check out this link. It tells you everything you need to know.
http://www.dyn-web.com/code/basics/random_image/random_img_js.php
Create array, put inside all image names (or their indexes if it's better for you) and then use something like this:
var images = ["/first.png", "/second.png", "/third.png", "/fourth.png", "/fifth.png"];
function takeImage() {
// if there is no more images in array, do something or return placeholder image
//if (!images.length) doSomething();
var image = images.splice(Math.floor(Math.random() * images.length), 1);
return image[0];
}
Basically, this function on each call will return one random image name (or index if you want) until there will be no images left in this array.
Simple, you save the last image out of the function. This makes a global variable. A global variable is a variable that exists in all functions, as a local variable only exists in the function itself (other functions cant use it).
// Define it outside of the function so the next time the called
// function gets it still has a value:
var lastNumber=0;
var imagesLength = randomImage.length; // don't recalc the amount of images every time
function getRandomImage(){
var number=0; // start a local variable
while( number == lastNumber){
number = Math.floor(Math.random()*imagesLength );
}
document.write('<img src="'+randomImage[number]+'" />');
}
To expand a bit on the local/global variables, lastNumber is global and can therefor be accessed in the function. var number however is local, it only exists in the function, console.log(number); outside the function would be undefined
To make a suggestion for improvement, document.write is best to be avoided. Browsers don't like them (*can't find doc's to support, feel free to edit), pre-create an image, even if its blank:
<img id="RandomImage" src="transparant.png" />
Now you make a global variable (this can only be done if the javascript is loaded after the image in the source, or with a document ready) to store the image, and use that:
// save reference to image, global (before the function):
var Image2Random = document.getElementById('RandomImage');
// place this instead of the document write.
Image2Random.src = randomImage[number];
This will be a lot faster. Javascript now knows what image to change, it doesn't have to create a new one every call (inserting elements to the DOM is expensive in resources), and the .src is really fast to change just the source.

How to place random elements in a HTML document using Javascript?

I´m developing a Javascript game and I have to place random coins in the HTML document. I have used this code so far:
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
}
This code simply places an image coin in the coordinates (0,0) of the document. What I want to do is access that recently created "div" and give it a random coordinate that I generate in another function so if I call several times the createCoin it creates several coins in the document. I can't use jQuery. Any ideas?
after create div element with id='coin' , to give the random position to div, use this:
<div id="coin" style="position:absolute">coin image</div>
<script language="javascript" type="text/javascript">
function newPos(){
var x=Math.random()*1000;
x=Math.round(x);
var y=Math.random()*500;
y=Math.round(y);
document.getElementById("coin").style.left=x+'px';
document.getElementById("coin").style.top=y+'px';
}
newPos();
</script>
we consider that createCoin() function execute once, on the onload() event. and then the newPos() function must be run.
Have createCoin return the div and then use it.
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
section.style.position = 'absolute';
section.style.left = '0px'; // units ('px') are unnecessary for 0 but added for clarification
section.style.top = '0px';
return section;
}
e.g.: var coin = createCoin(); coin.style.left = ???; coin.style.top = ???;

change image and caption

I am trying to work out a way to change the text that goes along with an image that is changed with javascript...
var x = 0;
var images = new Array(".jpg", ".jpg", ".jpg", ".jpg", ".jpg");
var i = setInterval(auto, 10000);
function auto() {
x++;
if (x == images.length) x = 0;
document.getElementById('bigImage').src = images[x];
}
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
/* document.getElementById('mainimagetitle').innerHtml = imagetitle; */
}​​​
The commented part is how i suppose I could possibly change the text that goes with the image. How do i code the html. Should i use a with the id mainimagetitle?
If so, where and how do i add the different texts i want to show and hide?
As I see from your posting, this should do the job.
<img id="bigImage" src="img1.jpg" alt="" />
<div id="mainimagetitle"></div>
Be sure to add a (filled) src tag or you will get strange results in IE. As you start with the second image (x++ before the change) this will be no problem. Happy accident I think. ;-)
// Edit: Of course any element will do as long as you use the right id. But you didn't tell us what html you use (xhtml/html5/...).
You could potentially have another array that stores the captions for each of the images
var captions = ['Caption 1', 'Caption 2', ...];
Assuming the mainimagetitle is an id of a <p> element, you could do:
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
document.getElementById('mainimagetitle').innerText = imagetitle;
}​​​
You can see the full example, based on your code here.

How can I use an algorithm to randomly generate a "map" using preset images?

I am working with some javascript to create a nice little image "map". I do not mean an image map like mapping out parts of an image, but I mean to have preset images form an array shown according a set pattern produced by an algorithm.
How can I make it so that the images have some sort of a basic pattern to them?
[edit 1]
I do understand that I would need to make the images form by columns at first, then by rows.
***I am now rewriting the format to do the above line.
If it helps, I would like the grass to be on top, then the dirt for three blocks under that, and then stone and cobble under those. The grass is always one layer deep, and I want air on the very top to give the blocks the sense of height. The air can be any height, but it needs to be one higher or lower then the ones next to it.
[/edit 1]
[edit 2]
Here is a link to what it does so far:
http://cl.ly/2s1h213E332r3i3v2a01
Here is a zip of the site so far:
http://cl.ly/1T0f2P1G333T1N1u0c31
I'm trying to make it look more organized like I discribed in [edit 1].
[/edit 2]
<html>
<body>
<script type="text/javascript">
var blockList = 'air,stone,grass,dirt,cobble,plank';
function blockGetId(ID) {
var blockGet = blockList.split(",")[ID];
return '<img src="images/' + blockGet + '.png" />';
}
function blockRandom() {
var blockCount = blockList.split(",").length;
var blockId = Math.round(Math.random()*(blockCount-1));
document.write(blockGetId(blockId));
}
function rowTable(width) {
var w = 0;
while ( w < width ) {
document.write('<td class="cell">');
blockRandom();
document.write(' </td>');
w++;
}
}
function blockTable(width, height) {
var h = 0;
document.write('<table class="cell"><style>.cell{width:16px;height:16px;colspacing:0px;margin:0px;padding:0px;}.cell hover{border: 5px;}</style>');
while ( h < height ) {
document.write('<tr class="cell">');
rowTable(width);
document.write('</tr>');
h++;
}
document.write('</table>');
}
blockTable(25,25);
</script>
</body>
</html>
Take a look at Amit Patel's blog about simple map generation. This could inspire you to an algorithm for map generation. The map uses Perlin noise.

creating an object/class and using it in jquery

Hi sorry if the name of my question is not correct.
i am trying to create an image rotator, but i would like to be able to re-use it more than once in a page, so i am trying to create it as an object/class.
I have about 5 or 6 images on a page.
i would like to have each image as a rotator, displaying a new image every 2 seconds or so.
<img src="uploads/Range_Images/p6-7.jpg" class="myclass1"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass2"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass3"/>
<script type=text/javascript>
$Rotator1 = new imageRotator1('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass1');
setInterval($Rotator1.rotateImage(), 1000);
$Rotator2 = new imageRotator1('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass2');
setInterval($Rotator2.rotateImage(), 1000);
$Rotator3 = new imageRotator1('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass3');
setInterval($Rotator3.rotateImage(), 1000);
</script>
Thats the code i am using to display the images and to create an instance of my rotator class
I can think of a few issues i am not sure of the answers too despite googling for hours!
Firstly here is my code (i am mixing javascript with jquery which is probably where i am going wrong to start with...
<script type="text/javascript">
$(document).ready(function(){ // maybe this should not be used when creating a object/class???
// i want to use this function as a class if possible
function imageRotator($images_str, $class){
// set up the vars
this.myImg = $images_str; //string containing image names
this.myClass = $class; //string containing class of image to change
this.imagelist = this.myImg.split(':'); //split the image string into an array
this.index = 1; // set the current index count
// maybe this is where i am going wrong, as in jquery $(this) refers to the current selector and maybe this.myclass (from from the imageRotator object does not work??
// is it possible to reference a value from an object in jquery?
function prototype.rotateImage(){
$(this.myclass).fadeOut('fast', function(){
$(this).attr('src', this.imagelist[this.index]);
$(this).fadeIn('fast', function(){
if (this.index == this.imagelist.length-1){
this.index = 0;
}else{
this.index++;
};
});
});
};
};
});
</script>
I am by no means an expert in programming, but i am sure this should be possible somehow.
any help would be much appreciated :P
update:
ok have modified the code slightly as per castrohenges reply:
<script type="text/javascript">
$(document).ready(function(){
var imageRotator = function($images_str, $class){
// set up the vars
this.myImg = $images_str; //string containing image names
this.myClass = $class; //string containing class of image to change
this.imagelist = this.myImg.split(':'); //split the image string into an array
this.index = 1; // set the current index count
};
function imageRotator.prototype.rotateImage(){
$(this.myclass).fadeOut('fast', function(){
$(this).attr('src', this.imagelist[this.index]);
$(this).fadeIn('fast', function(){
if (this.index == this.imagelist.length-1){
this.index = 0;
}else{
this.index++;
};
});
});
};
});
</script>
</head>
<body>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass1"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass2"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass3"/>
<script type=text/javascript>
$(document).ready(function(){
$Rotator1 = new imageRotator('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass1');
setInterval($Rotator1.rotateImage(), 1000);
$Rotator2 = new imageRotator('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass2');
setInterval($Rotator2.rotateImage(), 1000);
$Rotator3 = new imageRotator('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass3');
setInterval($Rotator3.rotateImage(), 1000);
});
</script>
</body>
i was getting an error: image rotator not defined on line 45
hence changing it to
var imageRotator = function($images_str, $class){....};
but the error is still there?
will try recreating this script following the plug-in guidelines and see where i get....
If you want to use prototyping you need to change
function prototype.rotateImage(){
and place it outside of the imageRotator function. Like so:
function imageRotator($images_str, $class){ ... }
imageRotator.prototype.rotateImage = function() { ... }
Alternatively you could also take a look at this jQuery plugin http://malsup.com/jquery/cycle/ - this is the first one I found, but I'm sure there will be more out there.
If you do want to use your own custom code I recommend wrapping it up as a jQuery plugin - http://docs.jquery.com/Plugins/Authoring. That way you don't have to worry to much about class architecture and everything will be nicely encapsulated in the jQuery object.

Categories