jQuery delay fadeIn - javascript

I have a javascript/jquery slideshow but I want to remove the somewhat long blank nothingness in between the fadein and fadeout images. I tried using a small delay because by default it still had a blank pause but that didn't work, any idea?
jsfiddle: https://jsfiddle.net/jzhang172/s624zn7d/1/
var imagesArray = ["http://assets.pokemon.com/assets/cms2/img/pokedex/full//007.png",
"http://assets.pokemon.com/assets/cms2/img/pokedex/full/001.png",
"https://assets.pokemon.com/static2/_ui/img/account/sign-up.png",
"http://static.giantbomb.com/uploads/scale_small/0/6087/2438704-1202149925_t.png",
"http://static.giantbomb.com/uploads/scale_small/0/6087/2438704-1202149925_t.png"];
function preloadImg(pictureUrls, callback) {
var i, j, loaded = 0;
var imagesArray = [];
for (i = 0, j = pictureUrls.length; i < j; i++) {
imagesArray.push(new Image());
}
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback(imagesArray);
}
};
img.src = src;
}(imagesArray[i], pictureUrls[i]));
}
};
function roll(imagesArray, currentPos){
var slide = $('.parallax-mirror').find('img').attr('src', imagesArray[currentPos].src);
slide.fadeIn(2000, function() {
slide.fadeOut(1500, function() {
currentPos++;
if(currentPos >= imagesArray.length){
currentPos = 0;
}
roll(imagesArray, currentPos);
});
});
}
$(function () {
preloadImg(imagesArray, function (imagesArray) {
roll(imagesArray, 0, 3);
});
});
.featured-wrapper {
height: 500px;
width: 100%;
overflow: hidden;
}
.things {
font-size: 50px;
height: 500px;
width: 100%;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parallax.js/1.4.2/parallax.min.js"></script>
<div class="featured-wrapper" data-parallax="scroll" data-image-src="http://assets.pokemon.com/assets/cms2/img/pokedex/full//007.png">
</div>
<div class="things">I'm the stuff underneath</div>

You should use an opacity animation with an easing that fits your needs. You can use jquery ui easings

Related

How do I programatically change a picture inside a div?

Here there is full code as you guys can see.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Collage</title>
</head>
<style>
div
{
background: url("Image/191203174105-edward-whitaker-1-large-169.jpg")
;
height: 300px;
width: 300px;
}
</style>
<body>
<div id="div"></div>
<button id="button">Next</button>
<script>
As here I took variable im where I feed 3 images.
var im=[
{'img':'Image/191203174105-edward-whitaker-1-large-169.jpg',}
,{'img':'Image/5718897981_10faa45ac3_b-640x624.jpg',},
{'img':'Image/gettyimages-836272842-612x612.jpg',},
];
var a=document.getElementById('button');
var b=document.getElementById('div')
a.addEventListener('click',next);
so here according to my knowledge it should provide the link of the each pic as loop starts but in program. I dont get the desired result. Can you please help me understand why this is happening?
function next()
{
for(var i=1;i<im.length;i++)
{
b.style.background=`url(${im[i].img})`;
}
}
</script>
</body>
</html>
var i = 0;
var im = [{
'img': 'https://picsum.photos/536/354'
},
{
'img': 'https://picsum.photos/id/237/536/354'
},
{
'img': 'https://picsum.photos/seed/picsum/536/354'
}
];
var a = document.getElementById('button');
var b = document.getElementById('div')
a.addEventListener('click', next);
function next() {
console.log(i);
b.style.background = `url(${im[i].img})`;
i++;
if (i == im.length) {
i = 0;
}
}
div {
background: url("https://picsum.photos/id/1084/536/354?grayscale");
height: 300px;
width: 300px;
}
<div id="div"></div>
<button id="button">Next</button>
If you're looking to cycle through pictures on a button click, then you can't really use a loop. In the code that you posted, on the click of the button, it rapidly looped through all of the pictures. You need to create a counter, and increment it on each button click.
The snippet below I've added in a previous button as well and you can cycle through the pictures both forward and backward.
const im = {
'img1': 'https://placehold.it/300x150/ff0000/ffffff?text=image_1',
'img2': 'https://placehold.it/300x150/00ff00/ffffff?text=image_2',
'img3': 'https://placehold.it/300x150/0000ff/ffffff?text=image_3',
};
const imgDiv = document.getElementById('imgDiv')
const btnNext = document.getElementById('btnNext');
const btnPrev = document.getElementById('btnPrev');
const totImages = Object.keys(im).length;
let imgNumber = 1;
btnNext.addEventListener('click', next);
btnPrev.addEventListener('click', prev);
function next() {
imgNumber++
let img = imgNumber <= totImages ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber === totImages) btnNext.disabled = true;
if (imgNumber > 1) btnPrev.disabled = false;
}
function prev() {
imgNumber--
let img = imgNumber >= 0 ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber < totImages) btnNext.disabled = false;
if (imgNumber === 1) btnPrev.disabled = true;
}
#imgDiv {
background: url("https://placehold.it/300x150/ff0000/ffffff?text=image_1");
height: 150px;
width: 300px;
}
#btnDiv {
width: 300px;
height: auto;
position: relative;
}
#btnPrev {
position: absolute;
left: 0;
top: 0;
}
#btnNext {
position: absolute;
right: 0;
top: 0;
}
<div id="imgDiv"></div>
<div id='btnDiv'>
<button id="btnPrev" disabled>&loarr; Prev</button>
<button id="btnNext">Next &roarr;</button>
</div>

How to repeat randomised img endlessly on javascript?

I have a function that render random image without repeating, but it stops working when the array of images has come to an end, my goal is to restart function with another random order of images, so function can work infinite. I've read another questions, but didn't find something appropriate to me case.
Here is html part:
<div class="card">
<div class="front" onClick="pickimg();return false;"><img
src="1.jpg" alt=""></div>
<div class="back"><img src="2.jpg" name="randimg"></div>
</div>
Css (just in case):
.card {
width: 200px;
height: 300px;
position: relative;
perspective: 1000px;
cursor: pointer;
margin: 0 50px;
}
.front, .back {
width: 100%;
height: 100%;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
transition: 1s;
backface-visibility: hidden;
border-radius: 10px;
}
.front {
transform: rotateY(360deg);
}
.back {
transform: rotateY(180deg);
}
And JS:
var cards = document.querySelectorAll('.card')
Array.from(cards).forEach(function(card) {
card.addEventListener('click', function() {
Array.from(card.querySelectorAll('.back, .front')).forEach(function(el) {
['back', 'front'].forEach(function(s) {
el.classList.toggle(s)
});
});
});
});
var usedImages = {};
var usedImagesCount = 0;
function pickimg(){
var imagenumber = 3;
var randomnumber = Math.random();
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array();
images[0] = "";
images[1] = "3.jpg";
images[2] = "4.jpg";
images[3] = "2.jpg";
var image = images[rand1];
if (!usedImages[rand1]){
document.randimg.src = images[rand1];
usedImages[rand1] = true;
usedImagesCount++;
if (usedImagesCount === images.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
pickimg();
}
}
Thank you for your help.
You could try something like this:
let img = [1,2,3,4,5];
function switchImage () {
for(; ; ){
let x = Math.random() * 10;
if(typeof img[Math.round(x)] !== 'undefined') {
img.splice(x, 1);
break;
}
}
console.log(img);
if (img.length > 0){
setTimeout(() => switchImage (),1000);
}
}
switchImage();
This is a simplified example where every second the function calls itself again and a new image is picked from the image array. The old image is cut out of the array and the function will stop calling itself when every picture is shown.
Try this -
int lastIndex = Math.round(Math.random()*(imagenumber - 1)) + 1;
function pickImg(){
let imagenumber = 3;
int currIndex = Math.round(Math.random()*(imagenumber - 1)) + 1;
images = new Array();
images[0] = "2.jpg";
images[1] = "3.jpg";
images[2] = "4.jpg";
if (lastIndex !== currIndex) {
document.randimg.src = images[currIndex];
lastIndex = currIndex;
}
else {
pickImg();
}
}
If you didn't get any image displayed that means you have to deal with when images[index] returns undefined.
Inshort you need to have index in images always equal to some value.
How about simple like this does this work for you? at least it will not give you same number a row
var imgArr = [1, 2, 3, 4, 5, 6] // imagine this is your img
var lastImgIndex;
function loadImg() {
var RandomIndex = Math.floor((Math.random() * imgArr.length) + 1);
if (lastImgIndex != RandomIndex) {
$('span').text(RandomIndex + ' index of img show');
lastImgIndex = RandomIndex;
} else {
loadImg();
}
}
loadImg();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>

My Javascript code doesn't run inside my MVC view

I'm having some issues implementing this template into my MVC application.
https://bootsnipp.com/snippets/featured/pinterest-like-responsive-grid
My CSS and code works fine, but the Javascript doesn't work.
I'm using a partial view to contain the code which looks like this:
#model List<Assignment_3.Models.Word>
<script type="text/javascript" src='#Url.Content("~/Scripts/ResponsiveGrid.js")'></script>
<div class="container">
<div class="row">
<div>
<section id="pinBoot">
#foreach (var word in Model)
{
<ItemTemplate>
<article class="white-panel">
<a href="#Url.Action("Detail", new { id = Word.WordId })">
<img src="#Url.Content(Idiom.Imagepath)" />
</a>
<h4 class="textwrapper">Test</h4>
<p>Language</p>
</article>
</ItemTemplate>
}
</section>
</div>
</div>
</div>
<style>
body {
background-color: #eee;
}
.textwrapper {
word-break: break-all;
}
#pinBoot {
position: relative;
max-width: 100%;
width: 100%;
}
img {
max-width: 100%;
height: auto;
}
.white-panel {
position: absolute;
background: white;
box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.3);
padding: 10px;
}
.white-panel h1 {
font-size: 1em;
}
.white-panel h1 a {
color: #A92733;
}
.white-panel:hover {
box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5);
margin-top: -5px;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
</style>
Here is the Javascript file:
$(document).ready(function () {
$('#pinBoot').pinterest_grid({
no_columns: 4,
padding_x: 10,
padding_y: 10,
margin_bottom: 50,
single_column_breakpoint: 700
});
});
usage:
$(document).ready(function () {
$('#blog-landing').pinterest_grid({
no_columns: 4
});
});
; (function ($, window, document, undefined) {
var pluginName = 'pinterest_grid',
defaults = {
padding_x: 10,
padding_y: 10,
no_columns: 3,
margin_bottom: 50,
single_column_breakpoint: 700
},
columns,
$article,
article_width;
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
var self = this,
resize_finish;
$(window).resize(function () {
clearTimeout(resize_finish);
resize_finish = setTimeout(function () {
self.make_layout_change(self);
}, 11);
});
self.make_layout_change(self);
setTimeout(function () {
$(window).resize();
}, 500);
};
Plugin.prototype.calculate = function (single_column_mode) {
var self = this,
tallest = 0,
row = 0,
$container = $(this.element),
container_width = $container.width();
$article = $(this.element).children();
if (single_column_mode === true) {
article_width = $container.width() - self.options.padding_x;
} else {
article_width = ($container.width() - self.options.padding_x *
self.options.no_columns) / self.options.no_columns;
}
$article.each(function () {
$(this).css('width', article_width);
});
columns = self.options.no_columns;
$article.each(function (index) {
var current_column,
left_out = 0,
top = 0,
$this = $(this),
prevAll = $this.prevAll(),
tallest = 0;
if (single_column_mode === false) {
current_column = (index % columns);
} else {
current_column = 0;
}
for (var t = 0; t < columns; t++) {
$this.removeClass('c' + t);
}
if (index % columns === 0) {
row++;
}
$this.addClass('c' + current_column);
$this.addClass('r' + row);
prevAll.each(function (index) {
if ($(this).hasClass('c' + current_column)) {
top += $(this).outerHeight() + self.options.padding_y;
}
});
if (single_column_mode === true) {
left_out = 0;
} else {
left_out = (index % columns) * (article_width +
self.options.padding_x);
}
$this.css({
'left': left_out,
'top': top
});
});
this.tallest($container);
$(window).resize();
};
Plugin.prototype.tallest = function (_container) {
var column_heights = [],
largest = 0;
for (var z = 0; z < columns; z++) {
var temp_height = 0;
_container.find('.c' + z).each(function () {
temp_height += $(this).outerHeight();
});
column_heights[z] = temp_height;
}
largest = Math.max.apply(Math, column_heights);
_container.css('height', largest + (this.options.padding_y +
this.options.margin_bottom));
};
Plugin.prototype.make_layout_change = function (_self) {
if ($(window).width() < _self.options.single_column_breakpoint) {
_self.calculate(true);
} else {
_self.calculate(false);
}
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin(this, options));
}
});
}
})(jQuery, window, document);
Any tips in getting the Javascript to work would be hugely appreciated!
It is a good practice to have your javascript files right before the closing body tag even though you are using jQuery and other open source libraries. Have you inspected the browser(F12 on windows) to see if the URL that you are pointing to is loading the file on the network? In MVC, you might want to put the JS file inside of bundle.config and referencing them using Bundling and Minification like the following
In Bundle.config
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
"~/Scripts/script.js");
In Application_Start Event
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
and
On the UI
#Scripts.Render("~/bundles/scripts")
This way , your JS files are minified and changes are always reflected onto the UI(Solves caching issues)
If you inspect the output html in your browser, you'll see that the url in your script tag probably doesn't resolve correctly:
<script type="text/javascript" src='#Url.Content("~/Scripts/ResponsiveGrid.js")'>
</script>
You can fix this by using a url relative to the root of the domain.
src="/Scripts/ResponsiveGrid.js"

jQuery - Image replacement transition [issues in Safari]

Okay I have the following code:-
[SEE JSFIDDLE]
HTML:
<div id="header">
<span class="mobile-menu"></span>
</div>
CSS:
#header {
width: 100%;
background: #000000;
height: 100px;
}
.mobile-menu {
position: absolute;
right: 25px;
top: 20px;
background: url(http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-01.png);
background-repeat: no-repeat;
background-size: 26px !important;
height: 26px;
width: 26px;
display: inline-block;
margin: 7px 0;
-webkit-transition-duration: 0.8s;
-moz-transition-duration: 0.8s;
-o-transition-duration: 0.8s;
transition-duration: 0.8s;
}
.mobile-menu-hover {
background: url(http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/mobile-menu-hover.png);
}
jQuery:
var imagesArray = ["http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-01.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-02.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-03.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-04.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-05.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-06.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-07.png"];
function preloadImg(pictureUrls, callback) {
var i, j, loaded = 0;
var imagesArray = [];
for (i = 0, j = pictureUrls.length; i < j; i++) {
imagesArray.push(new Image());
}
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback(imagesArray);
}
};
img.src = src;
}(imagesArray[i], pictureUrls[i]));
}
};
function changeImage(background, imagesArray, index, reverse) {
background.css("background-image", "url('" + imagesArray[index].src + "')").fadeIn(10, function() {
if (reverse) {
index--;
if (index == -1) {
return; // stop the interval
}
} else {
index++;
if (index == imagesArray.length) {
return; // stop the interval
}
}
//Fade in the top element
background.fadeOut(10, function () {
//Set the background of the top element to the new background
background.css("background-image", "url('" + imagesArray[index] + "')");
changeImage(background, imagesArray, index, reverse);
});
});
}
jQuery(function () {
/* Preload Image */
preloadImg(imagesArray, function (imagesArray) {
jQuery(".mobile-menu").css("background-image", "url('" + imagesArray[0].src + "')")
jQuery('.mobile-menu').on('click', {imgs: imagesArray}, function (event) {
var background = jQuery(".mobile-menu");
var bi = background.css('background-image');
var index = 0;
var reverse = false;
if (imagesArray[0].src != bi.replace('url("', '').replace('")', '')) {
index = imagesArray.length - 1;
reverse = true;
}
changeImage(background, event.data.imgs, index, reverse);
});
});
});
The Issue:
This works fine in Firefox and Chrome, it transitions between the 7 different images on click, then does the reverse on the second click (toggling).
The problem is when I try this in Safari, it basically goes through the image replacement process then reverts back to the first image for some reason and I can't figure out why?
Any ideas?
It seems to be because Safari returns the background-image without double quotes, but your replace function checks for url(", so it doesn't replace and reverse never gets true.
Instead of replacing you can check using either indexOf or matching using a RegExp, it would be safer and more straightforward. Either:
if ( bi.indexOf(imagesArray[0].src) == -1) {
or
if (imagesArray[0].src != bi.match(/http.+png/)[0]) {
With indexOf: http://jsfiddle.net/u9ske14r/

How would I make these animations animate at different times?

I'm making a whack-a-mole game and this is what I have so far, I'm aware this is sloppy and probably isn't the easiest/smartest way to do this. What I need to know is how to get my animations to animate at separate times. This current code works to animate 9 different moles coming out of holes but I need them to animate at different times(so none of them will come up at the same time, or within a few milliseconds of eachother) My current code is
<html>
<body>
<style type="text/css">
body, a, a:hover {cursor: url(http://cur.cursors-4u.net/others/oth-5/oth438.cur),
progress;}
</style>
<body background = "http://i52.tinypic.com/34e9ekj.jpg">
<b><center><font size="5"><div id='counter'>0</div></font></center><b>
<b><center><i>Whack-A-Mole</i> - by Steven</center></b>
<div
style="
top: 37;
left: 350;
position: absolute;
z-index: 1;
visibility: show;">
<center><img id='animation0' src ='http://i51.tinypic.com/sxheeo.gif'/></center>
</div>
<div
style="
top: 37;
left: 33;
position: absolute;
z-index: 1;
visibility: show;">
<left><img id='animation1' src ='http://i51.tinypic.com/sxheeo.gif'/></left>
</div>
<div
style="
top: 37;
left: 700;
position: absolute;
z-index: 1;
visibility: show;">
<right><img id='animation2' src ='http://i51.tinypic.com/sxheeo.gif'/></right>
</div>
<div
style="
top: 200;
left: 352;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation3' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 200;
left: 33;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation4' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 200;
left: 700;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation5' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 350;
left: 700;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation6' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 350;
left: 33;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation7' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 350;
left: 352;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation8' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
</body>
<head>
<script type="text/javascript">
var urls;
function animate0(pos) {
pos %= urls.length;
var animation0 = document.getElementById('animation0');
var counter = document.getElementById('counter');
animation0.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation0.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation0.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate0(++pos);
}, (Math.random()*500) + 1000);
}
function animate1(pos) {
pos %= urls.length;
var animation1 = document.getElementById('animation1');
var counter = document.getElementById('counter');
animation1.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation1.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation1.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate1(++pos);
}, (Math.random()*500) + 1000);
}
function animate2(pos) {
pos %= urls.length;
var animation2 = document.getElementById('animation2');
var counter = document.getElementById('counter');
animation2.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation2.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation2.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate2(++pos);
}, (Math.random()*500) + 1000);
}
function animate3(pos) {
pos %= urls.length;
var animation3 = document.getElementById('animation3');
var counter = document.getElementById('counter');
animation3.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation3.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation3.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate3(++pos);
}, (Math.random()*500) + 1000);
}
function animate4(pos) {
pos %= urls.length;
var animation4 = document.getElementById('animation4');
var counter = document.getElementById('counter');
animation4.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation4.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation4.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate4(++pos);
}, (Math.random()*500) + 1000);
}
function animate5(pos) {
pos %= urls.length;
var animation5 = document.getElementById('animation5');
var counter = document.getElementById('counter');
animation5.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation5.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation5.onclick = function() {
//do nothing onclick
}
}
setTimeout(function() {
animate5(++pos);
}, (Math.random()*500) + 1000);
}
function animate6(pos) {
pos %= urls.length;
var animation6 = document.getElementById('animation6');
var counter = document.getElementById('counter');
animation6.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation6.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation6.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate6(++pos);
}, (Math.random()*500) + 1000);
}
function animate7(pos) {
pos %= urls.length;
var animation7 = document.getElementById('animation7');
var counter = document.getElementById('counter');
animation7.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation7.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation7.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate7(++pos);
}, (Math.random()*500) + 1000);
}
function animate8(pos) {
pos %= urls.length;
var animation8 = document.getElementById('animation8');
var counter = document.getElementById('counter');
animation8.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation8.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation8.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate8(++pos);
}, (Math.random()*500) + 1000);
}
window.onload = function() { //Frames go below, seperated by commas format= , "URL");
urls = new Array("http://i51.tinypic.com/sxheeo.gif", "http://i56.tinypic.com/2i3tyw.gif");
animate0(0);
animate1(0);
animate2(0);
animate3(0);
animate4(0);
animate5(0);
animate6(0);
animate7(0);
animate8(0);
}
</script>
</head>
</html>
Generate 9 random numbers between 0 and your start time variation. Decide the max distance you want between the animations and scale the random numbers to that time frame. Then, set 9 timers to those times from now so each timer starts an animation.
If you wanted the animations to start over 500 milliseconds, you'd do something like this:
var randomTimes = [9];
for (var i = 0; i < 9; i++) {
randomTimes[i] = Math.floor(Math.random() * 501);
}
Now you have 9 random times spread out over 500 milliseconds and you can use those values with setTimeout to start each animation at a random time.
Copy/pasting a function this way is indeed sloppy!
You need to setup a flag:
var isMole = false;//at first there is no mole
if(!isMole){
//there is no mole, you can show one here
isMole = true;//there is a mole now!
}else{
//there is a mole, we wait.
}
Now set that flag to false when the mole times out or it struck by a hammer!

Categories