Need to set styling rules to a JavaScript image randomizing script - javascript

I am trying to set the background images to be fixed and be stretched to fit the screen. the js that i am using if to switch the backgroud image on every pageload
Head
<script language="JavaScript">
<!-- Activate cloaking device
var randnum = Math.random();
var inum = 1;
// Change this number to the number of images you are using.
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "http://simplywallpaper.net/pictures/2010/10/22/how_to_train_your_dragon_monstrous-nightmare.jpg"
images[2] = "tiler3.jpg"
images[3] = "wicker3.jpg"
images[4] = "aaa4.jpg"
// Ensure you have an array item for every image you are using.
var image = images[rand1]
// Deactivate cloaking device -->
</script>
Body
<script language="JavaScript">
<!-- Activate cloaking device
document.write('<body background="' + image + '" text="white" >')
</script>
The js itsself works fine to randomize the images but is currently set to 1 image

Simple, change both scripts to:
<script type="text/javascript">
var images = [ 'http://tinyurl.com/qhhyb8k'
, 'http://tinyurl.com/nqw2t9b'
, 'http://tinyurl.com/nkogvoq'
// , 'url 4'
]
, image = images[ (Math.random() * images.length)|0 ]
; //end vars
window.onload=function(){
document.body.style.background=
"url('"+image+"') no-repeat center center fixed";
document.body.style.backgroundSize=
"cover"; // width% height% | cover | contain
};
</script>
Nothing more to configure, just add/remove/change urls.
Example fiddle here.
Hope this helps.

inum needs to be set to something other than 1. You can set it to the number of images in the array.
Also, arrays start with index 0, so to be safer, you should index your array accordingly.
<script language="JavaScript">
// setup your image array
var images = new Array;
images[0] = "firstImage.jpg";
...
images[4] = "lastImage.jpg";
// alternative image array setup
var images = [ 'firstImage.jpg', 'secondImage.jpg', ... ,'lastImage.jpg' ];
// check to see if the image list is empty (if it's getting built somewhere else)
if (images.length) {
// set inum
var inum = images.length;
var randnum = Math.random();
var randIndex = Math.floor(randnum * inum);
// Ensure you have an array item for every image you are using.
var imageFile;
if (randIndex < images.length) {
imageFile = images[randIndex];
}
...
</script>
In the body
<script type="text/javascript">
window.onload = function() {
if (imageFile) {
var body = document.getElementsByTagName("body")[0];
if (body) { body.setAttribute('style',"background:url('"+imageFile+"'); text: white;"); }
}
}
</script>

Related

Random images load without repeat

Hi I found a script which loads images one after another into my div element. Everything works fine, but I would like it to load random images which do not repeat in a circle of all images.length.
Since I'm a total newb in this I tried to do something but most of the time I am able to load random images but without repeat check.
If you can, please help.
Thank you all in advance!
<script src="js_vrt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
//Initial Background image setup
image.css('background-image', 'url(' + images[i++] + ')');
//Change image at regular intervals
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1500);
});
if (i == images.length)
i = 0;
}, 5000);
});
</script>
You can use the shuffle method explained on the answer below.
How can I shuffle an array?
And get the first element on your array
image.css('background-image', 'url(' + images[0] + ')');
You may find a issue on this method, when the same image get loaded after shuffle the array. In this case, I recommend you to store in a variable the name of the last image shown, and before the array get shuffled, just test if the first element is equal the last image.
var lastImageLoaded ='';
setInterval(function() {
shuffle(images);
var imageUrl = images[0];
if(lastImageLoaded !== ''){ // Handle the first load
while(lastImageLoaded === images[0]){
shuffle(images);
}
}
lastImageLoaded = image;
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + imageUrl + ')');
image.fadeIn(1500);
});
Here is a complete object that takes in an array of image urls, and then displays them randomly until it has shown them all. The comments should be pretty explanatory, but feel free to ask questions if I didn't explain something enough. Here is a fiddle
//Object using the Revealing Module pattern for private vars and functions
var ImageRotator = (function() {
//holds the array that is passed in
var images;
// new shuffled array
var displayImages;
// The parent container that will hold the image
var image = $("#imageContainer");
// The template image element in the DOM
var displayImg = $(".displayImg");
var interval = null;
//Initialize the rotator. Show the first image then set our interval
function init(imgArr) {
images = imgArr;
// pass in our array and shuffle it randomly. Store this globally so
// that we can access it in the future
displayImages = shuffle(images);
// Grab our last item, and remove it
var firstImage = displayImages.pop();
displayImage(firstImage);
// Remove old image, and show the new one
interval = setInterval(resetAndShow, 5000);
}
// If there are any images left in our shuffled image array then grab the one at the end and remove it.
// If there is an image present in the Dom, then fade out clear our image
// container and show the new image
function resetAndShow() {
// If there are images left in shuffled array...
if (displayImages.length != 0) {
var newImage = displayImages.pop();
if (image.find("#currentImg")) {
$("#currentImg").fadeOut(1500, function() {
// Empty the image container so we don't have multiple images
image.empty();
displayImage(newImage);
});
}
} else {
// If there are no images left in the array then stop executing our interval.
clearInterval(interval);
}
}
// Show the image that has been passed. Set the id so that we can clear it in the future.
function displayImage(newImage) {
//Grab the image template from the DOM. NOTE: this could be stored in the code as well.
var newImg = displayImg;
newImg.attr("src", newImage);
image.append(newImg);
newImg.attr("id", "currentImg");
newImg.fadeIn(1500);
}
// Randomly shuffle an array
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
return {
init: init
}
});
var imgArr = [
"https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg",
"https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg",
"https://i.ytimg.com/vi/icqDxNab3Do/maxresdefault.jpg",
"http://www.funny-animalpictures.com/media/content/items/images/funnycats0017_O.jpg",
"https://i.ytimg.com/vi/OxgKvRvNd5o/maxresdefault.jpg"
]
// Create a new Rotator object
var imageRotator = ImageRotator();
imageRotator.init(imgArr);
you can try to make and array filled with 0's
var points = new Array(0,0,0, 0)
//each one representing the state of each image
//and after that you make the random thing
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
while (points[i]!=1){
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
}
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
points[i]=1;
image.fadeIn(1500);
});

Random image appear when website is loaded

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

JavaScript: set background image with size and no-repeat from random image in folder

I am a javascript newbie...
I'm trying to write a function that grabs a random image from a directory and sets it as the background image of my banner div. I also need to set the size of the image and for it not to repeat. Here's what I've got so far, and it's not quite working.
What am I missing?
$(function() {
// some other scripts here
function bg() {
var imgCount = 3;
// image directory
var dir = 'http://local.statamic.com/_themes/img/';
// random the images
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
// array of images & file name
var images = new Array();
images[1] = '001.png',
images[2] = '002.png',
images[3] = '003.png',
document.getElementById('banner').style.backgroundImage = "url(' + dir + images[randomCount] + ')";
document.getElementById('banner').style.backgroundRepeat = "no-repeat";
document.getElementById('banner').style.backgroundSize = "388px";
}
}); // end doc ready
I messed around with this for a while, and I came up with this solution. Just make sure you have some content in the "banner" element so that it actually shows up, because just a background won't give size to the element.
function bg() {
var imgCount = 3;
var dir = 'http://local.statamic.com/_themes/img/';
// I changed your random generator
var randomCount = (Math.floor(Math.random() * imgCount));
// I changed your array to the literal notation. The literal notation is preferred.
var images = ['001.png', '002.png', '003.png'];
// I changed this section to just define the style attribute the best way I know how.
document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();
Here's something sort of like what I use, and it works great. First, I rename all my background images "1.jpg" through whatever (ex. "29.jpg" ). Then:
var totalCount = 29;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg';
document.getElementById("div1").style.backgroundSize="100%";
document.getElementById("div1").style.backgroundRepeat="fixed";
}
Then run the function ChangeIt() .

Mouseover even in javascript wont output

Oh the splash screen of my new site I wish to have a mouseover event which will change the colour of my logo every time the mouse is moved. Below I have listed the code I have so far, but I cannot get it to display my image.
var images = new Array()
images[0] = 'img/CMbl.png'
images[1] = 'img/CMo.png'
images[2] = 'img/CMg.png'
images[3] = 'img/CMp.png'
images[4] = 'img/CMblu.png'
var p = images.length;
logo = document.getElementById( 'logo' ),
console = document.getElementById( 'console' );
logo.addEventListener('mousemove', changeImage);
function changeImage() {
var rand = Math.round(Math.random()*(p-1));
var image = p[ rand ];
if ( image == logo.src ) {
changeImage();
return false;
}
logo.src = console.innerText = image;
function showImage(){
document.write('<img src="+image[rand]">');
}
}
and my output in html should be (Inside the class 'logo')
<script language="javascript">
showImage()
</script>
I cannot see why it's not working. I am using a similar code to change image on refresh, which still uses math.random() and an array to call the images.
This is the way this should look:
document.write('<img src="' + image[rand] + '">');
(your script is full of mistakes from what I can see. I'll make a quick, working one for you as an example.)
Here is a working example(I think this is what you're going for) Jsfiddle example
As you can see, it comes out to a terrible looking effect, I wouldn't suggest using it.
I've made a JSfiddle which cleans up some of the code, and makes use of jQuery.
http://jsfiddle.net/jackcannon/2EXs5/
var images = [
'http://colorvisiontesting.com/plate%20with%205.jpg',
'http://regentsparkcollege.org.uk/wp-content/uploads/2012/09/test.jpg',
'http://nyquil.org/uploads/IndianHeadTestPattern16x9.png',
'http://25.media.tumblr.com/tumblr_m9p3n1vJmZ1rexr16o1_400.jpg',
'http://www.themoralofthestoryis.com/wp-content/uploads/2013/01/test.gif'
];
$('#logo').mouseover( changeImage );
function changeImage() {
var rand = Math.floor(Math.random() * images.length);
var image = images[ rand ];
if ( image == $('#logo').attr('src') ) {
changeImage();
return false;
}
$('#logo').attr('src', image);
};

change background img each time by clicking link

<body>
<script language="JavaScript">
<!--
var backImage = new Array();
backImage[0] = "pics/img02.jpg";
backImage[1] = "pics/img03.jpg";
backImage[2] = "pics/img04.jpg";
backImage[3] = "pics/img05.jpg";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
backImage = backImage++;
}
}
//-->
</script>
Change
</body>
sorry, i don't get how i exactly should properly integrate code here -hopefully it still worked. what i want to do here: change the background (that works) than add plus one to the background counter so that the next time the link is clicked the next background shows (that doesn't work). it should be quite simple but i couldn't figure it out nevertheless...
Use a static counter that counts from 0 to 3.
var cnt = 0;
function changeBGImage(){
if (document.body){
document.body.background = backImage[cnt];
cnt = (cnt+1) % 4; // mod 4
}
}
There are a couple of issues in your code
backImage = backImage++;
Doesn't increment backImage as you expect. The syntax should be simply backImage++;
Also, to set the background image you need document.body.style.background or document.body.style.backgroundImage = url(...)
Edit
Over and above cycling through the backgrounds via the click handler, if you also need to set the initial background, try something like below, with the initial background set in window.onload.
jsFiddle here
var backImage = [];
var whichImage = 0;
backImage[0] = "http://dummyimage.com/100x100/000000/000000.png";
backImage[1] = "http://dummyimage.com/100x100/FF0000/000000.png";
backImage[2] = "http://dummyimage.com/100x100/00FF00/000000.png";
backImage[3] = "http://dummyimage.com/100x100/0000FF/000000.png";
function changeBGImage(reseedWhichImage){
// If caller has specified an exact index, then reseed to this
if (reseedWhichImage != undefined)
{
whichImage = reseedWhichImage;
}
if (document.body){
document.body.style.backgroundImage = "url(" + backImage[whichImage] + ")";
whichImage++;
if (whichImage >= 4){
whichImage = 0;
}
}
}
// During global load, set the initial background
window.onload = changeBGImage(2);
​

Categories

Resources