Rotate random background images with crossfade transition - javascript

I have 15 background images in my website. They´re all 1024 x 768 px, and they load random each time the user load the page. Besides that, the images fill the entire screen, no matter what size the browser window is.
I´m stuck with something I want to accomplish, though: I want the images to randomly rotate every n seconds, using a cross fade transition. I´ve reading like a ton of tutorials regarding that subject, but still can´t figure it out.
Thanks in advance, guys!
This is the code:
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.fullscreenr.js" type="text/javascript"></script>
<script type="text/javascript">
var FullscreenrOptions = {width: 1024, height: 768, bgID: '#bgimg'};
jQuery.fn.fullscreenr(FullscreenrOptions);
var randnum = Math.random();
var inum = 15;
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "images/contactBG01.jpg"
images[2] = "images/contactBG02.jpg"
images[3] = "images/contactBG03.jpg"
images[4] = "images/contactBG04.jpg"
images[5] = "images/contactBG05.jpg"
images[6] = "images/contactBG06.jpg"
images[7] = "images/contactBG07.jpg"
images[8] = "images/contactBG08.jpg"
images[9] = "images/contactBG09.jpg"
images[10] = "images/contactBG10.jpg"
images[11] = "images/contactBG11.jpg"
images[12] = "images/contactBG12.jpg"
images[13] = "images/contactBG13.jpg"
images[14] = "images/contactBG14.jpg"
images[15] = "images/contactBG15.jpg"
onload=function(){
document.getElementById("bgimg").src=images[rand1];
}
</script>
</head>
<body>
<img id="bgimg" src="" />
<div id="realBody">
<img id="exampleDiv" src="images/contact_top.png"/><br>
<img id="exampleDivBottom" src="images/contact_pie.gif">
</div>
</body>
</html>

if jQuery is an option:
// Wait for DOM-ready, don't use `window.onload`
$(function() {
// The image we are going to be updating
var img = $("#bgimg"),
// The number of seconds between transitions
every = 15 * 1000,
// The speed at which to fade, can be: 'slow',
// 'medium, 'fast', or a number (in milliseconds)
fadeSpeed = "slow",
// The images to cycle through
imgs = [
"images/contactBG01.jpg",
"images/contactBG02.jpg",
"images/contactBG03.jpg",
"images/contactBG04.jpg",
"images/contactBG05.jpg",
"images/contactBG06.jpg",
"images/contactBG07.jpg",
"images/contactBG08.jpg",
"images/contactBG09.jpg",
"images/contactBG10.jpg",
"images/contactBG11.jpg",
"images/contactBG12.jpg",
"images/contactBG13.jpg",
"images/contactBG14.jpg",
"images/contactBG15.jpg"
];
// Use setTimeout to schedule the image to be updated
// periodically
setTimeout(function() {
// Fade the image out, then when done...
img.fadeOut( fadeSpeed, function() {
// Use the length of the array to generate a number
var newSrc = imgs[Math.round(Math.random * (imgs.length-1)) + 1];
// Replace the src, then fade back in
img
.attr("src", newSrc )
.fadeIn( fadeSpeed )
}, every );
});
hope that helps! cheers.

Related

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() .

Need to set styling rules to a JavaScript image randomizing script

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>

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

How to have div re-size itself to image on page load

So my goal is to have an image slideshow with 3 clickable hot spots at the bottom. I have the basic functionality of this down now, but my content div doesn't size itself properly until it loops through the images for the first time. I need everything to be sized and positioned correctly immediately when the page loads.
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#image").attr("src", images[0]);
});
//Click tracking
var badClicks = 0;
var skipClicks = 0;
var goodClicks = 0;
//Counter to keep track of images
var iCount = 0;
var images = [];
images[0] = "images/document.png";
images[1] = "images/document2.png";
images[2] = "images/document3.png";
function nextImage(){
iCount++;
//If there are no more images in the array, go back to the first image
if (images[iCount]==null) {
iCount = 0;
};
//Change image source to new image
$("#image").attr("src", images[iCount]);
//Set content wrapper width & height to current image's width & height
$("#content").css("width", $("#image").css("width"));
$("#content").css("height", $("#image").css("height"));
//Store content wrapper's new width and height into variables
var h = parseInt($("#content").css("height"));
var w = parseInt($("#content").css("width"));
//Move hotspot-wrapper to the bottom of the new image
//Height of content wrapper - height of hotspot wrapper = new top
$("#hotspot-wrapper").css("top", h - parseInt($("#hotspot-wrapper").css("height")));
console.log(images[iCount] + " h " + h + " w " + w);
}
//Do something with data for "bad" hotspot
function bad(){
badClicks++;
}
//Do something with data for "skip" hotspot
function skip(){
skipClicks++;
nextImage();
}
//Do something with data for "good" hotspot
function good(){
goodClicks++;
}
//Show the collected data
function displayResults(){
$("#results").append("<br />Bad: " + badClicks
+ " Skip: " + skipClicks
+ " Good: " + goodClicks);
}
</script>
</head>
<body>
<div id="content">
<img id="image" />
<div id="hotspot-wrapper">
<div id="hotspot-a" class="hotspot" onclick="bad();"></div>
<div id="hotspot-b" class="hotspot" onclick="skip();"></div>
<div id="hotspot-c" class="hotspot" onclick="good();"></div>
</div>
</div>
<br />
<div id="results" style="clear:both">
<button onclick="displayResults();" style="text-align: center">Show results</button>
</div>
Any help, tips or advice would be greatly appreciated!
Thanks!
First of all i prefer this way to init images array:
var images = [];
var image = new Image();
image.src = '/some/image/url.jpg';
/* while you doing this image already load in background - so its faster way*/
images.push(image);
You can display this images with jQuery this way:
$('#parend_of_image_div').html(images[iCount]);
And inside your nextImage function use this code:
var img = images[iCount];
$(img).load(function(){
var width = $(this).width()
var height = $(this).height();
/* do other stuff */
});
This is your problem
$("#image").css("width")
However, you havent set #image's width with css. You need to use
$('#image').width()
Also, to be safe, you should only continue with this part of the code AFTER your image has triggered a load event:
//Change image source to new image
$("#image").attr("src", images[iCount]).load(function(){
//Set content wrapper width & height to current image's width & height
$("#content").css("width", $("#image").width());
$("#content").css("height", $("#image").height());
//And then the rest...

Categories

Resources