<div id="dragon" style="position: absolute; left: 600px; top: 400px; " onload="timeimgs('9');">
</div>
<script language="JavaScript">
var anim_images=new Array();
//putting drag0 to drag9 png into the anim_images array
for (i=0;i<=10;i++) {
var name;
name=eval("drag" + numb + ".png");
anim_images.push("name");
}
function imgturn(numb) {
if (numb == "9") { // This will loop the image
//getting the image of the array when reach 9
document["demo"].src=anim_images[9];
//starting again with drag0.png?
timeimgs('0');
}
else {
document["demo"].src=anim_images[numb];
timeimgs(numb = ++numb);
}
}
function timeimgs(numb) { // Reusable timer
thetimer = setTimeout("imgturn('" +numb+ "')", 1000);
}
</script>
Right now, it isn't working yet. it set the drag0.png to 200 width and 200 height. and I want to animate drag0.png to drag9.png continuously.
Any inputs are appreciated.
HTML:
<div id="dragon" style="position:absolute; left:60px; top:40px; width:640px; height:480px; "></div>
JAVASCRIPT:
function animateImagesStart() {
// next array generation code only for my sample/test: comment it or delete
var imgs=[
"http://4.bp.blogspot.com/-PilKprMNhpo/TVc4rKk_gKI/AAAAAAAAAWo/O3wPK3kIH_8/s640/two_flowers.preview.jpg",
"http://1.bp.blogspot.com/-4-NEunVEZxA/TWendjaBwOI/AAAAAAAAAAU/KKO4MDt5xJ0/s640/10_4_orig.jpg",
"http://4.bp.blogspot.com/-pc9ImOpPTs0/TaxDIYd5JnI/AAAAAAAAA_M/PF8b7H3nCs8/s640/ocean-flowers.jpg",
"http://4.bp.blogspot.com/-3CjVKRE6kXE/Ti_Gy6fXKuI/AAAAAAAAG3k/-er17XD7uJc/s640/cherry-blossom-pink-flowers-3.jpg",
"http://whatscookingamerica.net/EdibleFlowers/LavenderFlowers.jpg",
"http://www.photographyblogger.net/wp-content/uploads/2010/05/flower23.jpg",
"http://1.bp.blogspot.com/_24bCsL1xWcM/S6ob05W5KbI/AAAAAAAAAOQ/ZEQK9aiR-nQ/s1600/Flowers.jpg",
"http://3.bp.blogspot.com/_NjdBzKI5nYs/Sc79kMCKxZI/AAAAAAAABu8/vfk6RrGzpPw/s640/flower+sky+wallpaper+image+photo+pic.jpg",
"http://4.bp.blogspot.com/-ik3E8PBBf70/TwaZ9PMNbrI/AAAAAAAAAG0/kNrGnEbZ-WY/s1600/flowers2.jpg",
"http://www.funeral-flowers-online.com/funeral-flowers.jpg"
];
// next array generation code based on your code: uncomment it
/*
var imgs=[];
for(var i=0;i<10;i++)imgs.push("drag"+i+".png"); // 10 images
*/
// preloading images
var img,count=imgs.length,
imageLoadComplete=function(ev) {
if(ev.type=="error")imgs.splice(imgs.indexOf(this),1);
};
for(var i=0;i<count;i++){
img=new Image();
img.onerror=imageLoadComplete;
img.src=imgs[i];
imgs[i]=img;
}
var domImg=document.getElementById("dragon"),
currentImageIndex=0,
animateImages=function(){
if(currentImageIndex>=imgs.length)currentImageIndex=0;
if(imgs[currentImageIndex].complete)domImg.style.backgroundImage="URL("+imgs[currentImageIndex].src+")";
currentImageIndex++;
setTimeout(animateImages,1000);
};
setTimeout(animateImages,0);
}
if(window.addEventListener)window.addEventListener("load",animateImagesStart,false);
else if(window.attachEvent)window.attachEvent("onload",animateImagesStart);
Insure that each of your images has same size (width and height) as DIV#dragon or replace DIV#dragon with IMG#dragon html element and use IMG src property instead of style.backgroundImage. Example: http://jsfiddle.net/RK7u9/1/
Related
I am loading images from my unsplash collection (https://unsplash.com/collections/3132360/dashboard) and changing the background image of the body (through CSS). It works, but there is a delay in the change. Is there a way I can preload the images and maybe even fade them in/out?
I have tried the new Image() of javascript, but that is for HTML images and not CSS.
Thanks in advance :)
Here is the jquery:
$('document').ready(function(){
var x = 0;
loadImage(x);
});
function loadImage(x) {
x +=1;
var image = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x;
setTimeout(function() {
imgSwap(image, x);
}, 30000)
}
function imgSwap(image, x){
$('body').css('background-image', 'url(' + image + ')');
loadImage(x);
}
You can add default image to body style in css to show the preload image.
body{
background-image: url("http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/5-1.gif");
background-repeat: no-repeat;
}
https://jsfiddle.net/nimittshah/cwpdsnLy/
This updated code now works, using img.src as the background URL for the CSS refreshes the image as needed. Using just the image variable as the URL does not.
$('document').ready(function(){
var x = 0;
loadImage(x);
});
function loadImage(x) {
x +=1;
var image = new Image()
image.src = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x;
setTimeout(function() {
imgSwap(image, x);
}, 30000)
}
function imgSwap(image, x) {
$('body').css('background-image', 'url(' + image.src + ')');
loadImage(x);
}
I think if you can include this following javascript code and css, it might be able to full fill what you want to achieve
function preloader() {
if (document.getElementById) {
document.getElementById("preload-01").style.background = "url(http://domain.tld/image-01.png) no-repeat -9999px -9999px";
document.getElementById("preload-02").style.background = "url(http://domain.tld/image-02.png) no-repeat -9999px -9999px";
document.getElementById("preload-03").style.background = "url(http://domain.tld/image-03.png) no-repeat -9999px -9999px";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }
#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }
var x = 0;
$('document').ready(function(){
loadImage(x);
});
function loadImage(x) {
setInterval(function() {
var randomId = new Date().getTime();
var image = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x+'?r='+randomId;
console.log("x="+x + " " + image);
imgSwap(image);
x +=1;
}, 30000)
}
function imgSwap(image){
$('body').css('background-image', 'url(' + image + ')');
//$('#bg_img').attr('src', image);
}
You can change value of x randomly, but i have found your img provider is not returning the images plz check this first, It is redirecting to some other url
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!--<img id="bg_img" src="" width=400 height=400/>-->
I'm working on a Javascript assignment that splits the page into two div elements then appends the div on the left with randomly placed images, then I used .cloneNode() to duplicate on the right, minus the last child image.
That part of it works fine, but I am then supposed to add an event handler to the last element of the left div, but when I try to do this the lastElementChild() method returns null even though the div has the expected child nodes. The code is below and I've commented where the problem is. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
<style>
img {position: absolute}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
<script>
<!-- everything here works fine -->
function generateFaces(){
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++){
var random_x = Math.random()*400;
var random_y = Math.random()*400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
}
</script>
</head>
<body onload = "generateFaces()">
<h1> Game </h1>
<p> Instructions </p>
<div id = "right"></div>
<div id = "left"> </div>
<script>
<!-- problem script here -->
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // returns null
</script>
</body>
</html>
The body's onload event will not fire until after the javascript in your 'problem script' runs.
The order of execution here is basically:
h1, p, #left, and #right get appended to the DOM
script #1 runs, logging the empty #left div and the null lastElementChild.
body onload event fires and script #2 runs (the generateFaces() function). At this point, the <img> tags are inserted into the DOM.
The fix is to make sure that script #1 runs after #2:
<body onload="handleLoad()">
and the JS:
function handleLoad() {
generateFaces()
logStuff()
}
function logStuff() {
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // logs <img>
}
It might appear, in the console, that #left has images in it at the time that script #1 runs. This is just a quirk of the console; the actual logging happens asynchronously, and since the referenced variable changes in the meantime, the value actually logged is different than what it was when console.log() was called.
You can see this behavior by varying a setTimeout duration on the generateFaces() function call:
function generateFaces() {
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++) {
var random_x = Math.random() * 400;
var random_y = Math.random() * 400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style", "top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
}
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // returns null
setTimeout(generateFaces, 250) // play with this value
img {
position: absolute
}
div {
position: absolute;
height: 500px;
width: 500px
}
#right {
border-left: solid black;
left: 500px
}
<h1> Game </h1>
<p> Instructions </p>
<div id="right"></div>
<div id="left"> </div>
Oh, and note that your generateFaces() function currently creates multiple elements in the DOM with the same id. You're gonna want to fix that.
Your generateFaces() function is called when the body is loaded.
but your second script runs when the window is loaded.
So when the second script runs there is no temp.lastElementChild and you get null.
You can slove is like this
<!DOCTYPE html>
<html>
<head>
<style>
img {position: absolute, height: 30px; width: 30px;}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
</head>
<body onload = "generateFaces()">
<h1> Game </h1>
<p> Instructions </p>
<div id = "right"></div>
<div id = "left"> </div>
<script>
function generateFaces()
{
console.log('y');
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++){
var random_x = Math.random()*400;
var random_y = Math.random()*400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
loaded();
}
<script>
function loaded() {
var temp = document.getElementById("left");
console.log(temp);
var temp2 = temp.lastElementChild;
console.log(temp2);
}
I wrote the code in Javascript but any good alternative would do.
EFFECT: onmousemove over the webpage circles of random colors should create wherever the mouse moves. and they have to be added behind a mask image(circles are visible only in the transparent portion of the image which is a logo. thus creating a color paint to create logo onmousemove.
it doesn't work in jsfidde because of its memory intensiveness.
WORKING LINK: http://goo.gl/DNRxO9
I pasted the exact code you can create a new html file with the following code and IT WORKS PERFECT IN FIREFOX ONLY because of its memory intensiveness(lots of divs added in very short time so DOM becomes very very heavy).
<html>
<head>
<style type="text/css">
body{
padding:0;
margin:0;
overflow: hidden;
}
#mask{
width:100%;
height:auto;
position:absolute;
z-index:10;
}
#logo{
width:50%;
height:50%;
margin:auto;
}
.point{
width:0px;
height:0px;
background-color:#ff0000;
position:absolute;
z-index:5;
left:50px;top:50px;
border-width:50px;
border-style: solid;
border-color:red;
border-radius:50px;
opacity:1;
transition: border-width 3s ease-in-out;
}
.no-border{border-width:0px;}
</style>
<script type="text/javascript">
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
/* OptionalCode: for removing divs after a lot are created */
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
i=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
var point = document.getElementsByClassName('point');
document.body.innerHTML += "<div class='point'></div>";
point[i].style.borderColor = getRandomColor();
//point[i].className += ' no-border';
point[i].style.left = x + 'px';
point[i].style.top = y + 'px';
i++;
}
function position(){
var ht = window.getComputedStyle(document.getElementById("mask"), null).getPropertyValue("height");
var ht_num = Number(ht.slice(0,ht.length - 2));
margin_top = (Number(document.body.clientHeight) - ht_num)/2;
document.getElementById('mask').style.marginTop = margin_top + "px";
}
</script>
</head>
<body onload="position();" onmousemove="colors(event)">
<img id="mask" src="http://goo.gl/EqfJ0L">
</body>
</html>
There is one HUGE, HUGE, HUGE performance killer in your code:
document.body.innerHTML += "<div class='point'></div>";
This takes your entire document, throws it away and just inserts everything back again. This is horrible! Remember this for all times and never do this again! ;)
Keep the basic rule in mind, to never add Elements via .innerHTML!
The correct way to go is the following:
// create your new div element
var circleElement = document.createElement("div");
// add all the stuff needed
circleElement.classList.add("point");
circleElement.style.borderColor = getRandomColor();
circleElement.style.left = x + 'px';
circleElement.style.top = y + 'px';
// now append the element to the body
document.body.appendChild(circleElement);
This creates a single div and nicely inserts it as a child-element of the body.
Additionally you can decrease the number of divs drawn by introducing a threshhold:
var lastX=0,lastY=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
if (Math.abs(lastX - x) + Math.abs(lastY - y) <= 10 ) return;
/* do stuff */
lastX = x;lastY = y;
}
As a third measure you can decrease the size of the image to just hold the mask element and trigger the mousemove only on the image (because divs outside the mask are hidden anyway).
Ultimately, you could kill "old" div-elements when you have reached a certain amount.
I have not included these two last optimizations, but look at the already supersmooth example now!
I have made this minimal test jsfiddle to show images and navigate with thumbnails, next and previous and also run as a slideshow.
It seems to be working OK, except that I can not get the current displayed image to fadeOut prior to the fadeIn of the next image.
Initially all the images were placed in a stack in the #holder DIV and then FadeIn and FadeOut worked as I expected, but I need to have the images in an array and load as required, because there will be several different values, associated with each image.
I probably have made some fundamental mistake or I do not understand how FadeIn and FadeOut properly work, as I am not an expert in javascript and jquery and I just get by, by looking at examples on here and similar sites.
I suspect I may need to somehow force a delay before loading the next image, but I can not work out how to do that.
Thanks
<style type='text/css'>
#holder { position: absolute; top: 100px; background-color:#CCCCCC;
width: 300px; height: 200px;
}
.slides { position: relative; top: 0px;
display: none;
}
#thumbs li
{
display: inline;
list-style-type: none;
padding-right: 6px;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
// define Global Vars
var timerON = null;
var files = [
["http://dummyimage.com/300x200/000/fff&text=Array-01", "http://dummyimage.com/40x40/000/fff&text=01","Title-01"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-02", "http://dummyimage.com/40x40/000/fff&text=02","Title-02"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-03", "http://dummyimage.com/40x40/000/fff&text=03","Title-03"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-04", "http://dummyimage.com/40x40/000/fff&text=04","Title-04"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-05", "http://dummyimage.com/40x40/000/fff&text=05","Title-05"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-06", "http://dummyimage.com/40x40/000/fff&text=06","Title-06"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-07", "http://dummyimage.com/40x40/000/fff&text=07","Title-07"]
]
var numImages = files.length;
// initial routines
showImage(1);
buildThumbs();
function showImage(num) {
//$('#holder img').fadeOut();
if ( $('#holder img').length > 0 ) { // fadeout existing
$("#holder img").fadeOut(700);
//alert("Faded OUT");
}
$("#holder").html('<img id="' + num + '" src="' + files[num-1][0] + '" style="display:none;"' + '" />');
$("#holder img").fadeIn(700);
//alert("Faded IN");
}
function buildThumbs() {
var thumbs = "";
for (cnt=0; cnt<files.length; cnt++) {
thumbs += '<li><a href="#" id="' + (cnt + 1) + '"><img src="' + files[cnt][1] + '" /></li>';
}
$('#thumbs').html(thumbs);
}
// Initialise routines for acting on click events
$(document).ready(function() {
$('#prev').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == 1) {
// at first position
}
else {
showImage(currImage-1); }
});
$('#next').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
// at last position
}
else {
showImage(currImage+1);
}
});
$('#thumbs a').click( function () {
var selImage = parseInt($(this).attr('id'));
var currImage = parseInt($('#holder img:visible').attr("id"));
showImage(selImage);
});
$('#slideShowBtn').click( function () {
slideShowCheck();
});
});
function slideShowCheck() {
if(timerON != null) {
clearTimeout(timerON);
timerON = null;
$('#slideShowBtn').text('Play Slideshow');
} else {
$('#slideShowBtn').text('Stop Slideshow');
slideShow();
}
}
function slideShow() {
var nextImage = 0;
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
nextImage = 1;
} else {
nextImage = currImage + 1;
}
showImage(nextImage);
timerON = setTimeout(slideShow, 3000);
}
});//]]>
</script>
</head>
<body>
<p>
<button id="prev">« Prev</button>
<button id="next">Next »</button>
</p>
<ul id="thumbs">
</ul>
<p>
<button id="slideShowBtn">Play Slideshow</button>
</p>
<div id="holder">
</div>
<div style="clear:both;"></div>
<ul id="thumbs2">
</ul>
</body>
</html>
Callbacks, callbacks, callbacks.
JS does alot of things async, so you will need to make use of a callback on that fadein.
$(ITEM1).fadeOut("fast", function() {
alert("all the way faded out");
$(ITEM2).fadeIn("fast");
});
Here's your fixed fiddle.
http://jsfiddle.net/MAaVV/
Above is the JSFiddle for my code. It's some CSS to make an image full screen, and then a simple src change for the image. I want to change image backgrounds every 5 seconds. It's below as well:
<STYLE type=text/css>
#bg {
position: fixed;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
#bg img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
}
</style>
<script type="text/javascript">
for(var x = 0; x < 2; x++)
{
setTimeout(function()
{
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg","http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg","clf.jpg"];
document.getElementById("img").src = imgs[x];
},5000);
}
</script>
<div id="bg">
<img id="img" src="http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg?w=919&h=613" alt="" />
</div>
Anyone know why it isn't working?
Bonus points for building in a redirect (to another website) after the last image of the slideshow is shown for 5 seconds.
Try this:
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg", "http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg"];
var i=0;
setInterval(function () {
document.getElementById("img").src = imgs[i];
if(i==1)
{
//alert('test');
$("#img").click(function(){
alert('on');
location.href='http://www.google.com';
});
}
if(i++>=1) i=0;
}, 5000);
Fiddle: http://jsfiddle.net/MAaVV/6/
Your code fails for two reasons:
You set all three (or two in th case of the jsFiddle) timeouts to run at the same time. Your code sets all three to run 5 seconds after the call, but all the calls are made at the same time, so they'll all run 5 seconds later.
You use the x variable in your timeout function, but it is not defined in the scope for that function. So, in all cases, the image is getting 'undefined' as the src.
To fix this, I'd use something like this:
<script type="text/javascript">
var imageIndex = 0;
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg","http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg","clf.jpg"];
setInterval(function(){
document.getElementById("img").src = imgs[imageIndex++];
if(imageIndex >= imgs.length) imageIndex = 0;
},5000);
</script>
http://jsfiddle.net/MAaVV/5/
EDIT: To make the function do something after all the slides have shown, you might try something like this:
<script type="text/javascript">
var imageIndex = 0;
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg","http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg","clf.jpg"];
var interval = setInterval(function(){
document.getElementById("img").src = imgs[imageIndex++];
if(imageIndex >= imgs.length){
clearInterval(interval);
setTimeout(function(){
// do whatever you want here, after a 5 second pause
},5000);
},5000);
</script>
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg", "http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg"];
var currentImage = 1;
$(document).ready(function(){
setInterval(function(){
if (currentImage >= imgs.length)
{
currentImage = 0;
window.location.href = 'http://www.google.com';
}
else
{
currentImage++;
}
$("#bg #img").attr("src", imgs[currentImage]);
}, 5000);
});
http://jsfiddle.net/MAaVV/2/