load random image from array to a css background - javascript

I am a js newbie. I Have looked for answers to this particular issue but have not found an answer yet in this forum or others, so sorry if it's here and I missed it. I have a script that works for loading a random image from an array to an id element placed directly in the html when the page loads.
I'm trying to see if I can get it to do the same thing but do it for a background image in a id element in a css file. I have firebug and it doesn't give me any error messages with this but it doesn't work either.
window. onload = choosePic;
var myPix = new
Array("images/image1.gif", "images/image2.gif");
function choosePic() {
randomNum = Math.floor((Math.random() * myPix.length));
document.getElementById("headerAnimation").style.backgroundImage.src = myPix[randomNum];
}

You have it almost right.
window.onload = choosePic;
var myPix = new Array("images/image1.gif", "images/image2.gif");
function choosePic() {
var randomNum = Math.floor((Math.random() * myPix.length));
document.getElementById("headerAnimation").style.backgroundImage =
"url(" + myPix[randomNum] + ")";
}

Related

Random Image button leads to new html page

I have a random image button and everytime I click it, it ends up randomizing the pictures in a new blank html page. Not the current html page I'm in.
<script type = "text/javascript" src = "page3.js">
function randomImg1() {
var myImages1 = new Array();
myImages1[1] = "beeDraw.jpg";
myImages1[2] = "blackattack.jpeg";
myImages1[3] = "bee1.png";
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.write('<img class="bee" src="' + myImages1[rnd] + '">');
}
</script>
Can someone look over this?
As opposed to using document.write I recommend you use access the DOM of your HTML page and get the image you want by ID. Then set the src equal to your new image.

Fade In don't work

I have wrote this javascript to show some images with id: imgFotogramma1/imgFotogramma2/ecc.. randomly in 8 different div with id Fotogramma1/Fotogramma2/ecc..:
function rullino() {
var immagini = new Array("strutture/1.jpg", "strutture/2.jpg", "strutture/3.jpg", "strutture/4.jpg", "strutture/5.jpg", "strutture/6.jpg", "strutture/7.jpg", "strutture/8.jpg", "strutture/9.jpg");
for (i = 1; i < 9; i++) {
var x = Math.floor(immagini.length * Math.random(1));
var imgId = "imgFotogramma" + i;
$(function () {
$(imgId).fadeIn(1000);
src = $(imgId).attr('src');
src = immagini[x];
alert(src);
});
}
setInterval("rullino()", 4000);
};
Now,this code start when body is loaded and its repeated every 4 seconds but i don't understand why the images are not displayed. I have started to work with Jquery not too much time ago and probably something are wrong.
I want to specify that: if i use normally javascript to assign to the src attribute the value of immagini[x],all work fine and the images are displayed.I have problem only to apply the fadein() motion.
I need a help to understand where is wrong,i have studied the fadeIn() API and i have tried to apply to my case.
Thanks in advance to anyone want to help me.
$(imgId).fadeIn(1000);
should be:
$('#'+imgId).fadeIn(1000);
Use # + idOfElemnt to select element with particular id.
You already doing it right. Just replace
var imgId = "imgFotogramma"+i;
With
var imgId = "#imgFotogramma"+i;
Since your are using the ID of the image, then your must have to use the "#" for id for applying the jQuery on it.
To select an ID, use # + elemID. Like this:
var imgId = "#imgFotogramma" + i;
Also, fade will not occur if the element is not hidden. First hide it, and then fade it in:
$(imgId).hide().fadeIn(1000);

get name of files in a folder with javascript

I have a background image folder that there is some picture that i want to use them for background.
how i can get their names and put them on array whit javascript?if i cant they do with javascript,how can i do that?
i want to read name of files and use javacsript and link for change background image whit css.
<script>
function nextbg(){
$('#bg').css('background-image','url(Images/bg2.jpg)');
}
</script>
This solution is created according to the fact that browser dont have access to folders/filesystem.
Javascript can not access the filesystem. This has to be done by a server script and then be feed to the javascript.
I had the simliar problem when building my game engine when I was loading all my diffrent tiles. I ended up doing it like this.
This solution do pose two a problems when implementing it.
You will have to define the amout of images in the "NrofTiles" array
The images must be named like tile1, tile2 ... tile9 so you can
increment the path to them.
The typeOfTiles[typeCounter] is just there to give me access to different folders, in my case for my tiles, grass, houses, water and so on.
for(var i = 0; i <= nrofTiles.length; i++)
{
for(var x = 0; x <= nrofTiles[i]; x++)
{
console.log
("Fetching tile "+(x + 1 )+" of " + 14);
img = new Image();
//My path
img.src = 'Images/Cart/' + typeOfTiles[typeCounter] + '/' + (x + 1) + '.png';
imgArray.push(img);
var intervalFunctionen = function () {
alert("calls back here");
};
}//end for loop!
}end outer for loop!
When everything is loaded(the tiles), you do this to change the background picture.
This is an example of a changing body background. You could make a link with an ID lets say "iamthelink".
HTML
Change BG
JAVASCRIPT
var link = document.getElementsById('iamthelink');
link.onclick= function() {
var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';
}

Showing random divs images every time page is load

Lets say I have these images gallery, how do i randomly display the images everytime when i reload the page?
http://creativepreviews.com/fiddle/study/20131007/
Let's say the image will display in the background of the DIV, then the following should do it.
// JS
var imgArray = ["img1.jpg", "cat.jpg", "sky.jpg"]
function randomBg() {
x = Math.random()
y = Math.round(x * 10)
if (imgArray[y] != undefined) {
document.getElementById("blah").style.backgroundImage = "url('" + imgArray[y] + "')"
} else {
document.getElementById("blah").style.backgroundImage = "url('default.jpg')"
}
}
...and the HTML.
<script src="test.js"></script>
<body onload="randomBg()">
<div id="blah"></div>
...or you could replace the style.backgroundImage in the JS with innerHTML = <img src=" etc...
You could do something along these lines (not tested)
var grd = $('#grid');
var imgs = grd.children();
imgs.sort(function(){return (Math.round(Math.random()) - 0.5);});
grd.remove('li');
for(var i=0;i < imgs.length;i++) grd.append(imgs[i]);
In essence what we are doing is getting all the li elements in 'grid' into an array, randomizing them, removing them all from 'grid' and then putting them back in again.
If you had supplied a working fiddle rather than a link to the finished article it would be easier to modify it and provide a more complete solution.

I can change background images, but how to print link?

I am using JavaScript to randomly change the background image upon refresh. What I have been wanting to do is then take the current background-image url and paste it in a certain div within
so that people can download the image.
The background image script works and is as follows:
var totalCount = 3;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
Sorry if this is easy but I haven't been able to figure out how to do it! Can anyone point me in the right direction?
Let's assume you have this link somewhere in your document and you want it to point to the current background image:
<a href='#' id='bgDownload'>Download background image</a>
The following function changes now the "href"-attribute of the link to the current background and the background itself:
var totalCount = 3;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
// change link
document.getElementById("bgDownload").href = 'bgimages/'+num+'.jpg';
}
I hope it helps...
Put a DIV on your page in the HTML, and switch the content using...
document.getElementById("[ID of DIV]").innerHTML = '' + [text_var] + '';
Something like this...
document.getElementById("[ID of DIV]").innerHTML = 'Image #' + num + '';
Try this
<a href='javascript:window.location.href=document.body.background'>
Download Background
</a>
try this :  
  
function downloadImage{
window.open(document.body.background,'_blank');
}

Categories

Resources