GIFs changing randomly - javascript

I got a problem with GIFs and Javascript. I got different GIF-animations which are all the same format and I want them to change randomly after they are played one time.
I tried to solve this with Javascript but I only could make it work with an exact time to make the change and not when each GIF-animation is finished (they are all finishing at different times).
<html>
<head>
<script type="text/javascript">
<!--
var ima = [];
ima[0] = 'bilder/bild1.gif';
ima[1] = 'bilder/bild2.gif';
ima[2] = 'bilder/bild3.gif';
ima[3] = 'bilder/bild4.gif';
function BildWechsel()
{
var num = Math.random();
var ran = Math.floor((ima.length - 1) * num);
document.images['wechsel'].src = ima[ran];
}
onload = function ()
{
window.setInterval(function () { BildWechsel(); }, 10000);
}
//-->
</script>
</head>
<body>
<img id="wechsel" src="bilder/bild1.gif" border="0" alt="">
</body>
</html>
Is there any possibility to make this work? And if not in a browser, how else can you maybe make it work?

I would rewrite the Javascript like this:
window.onload = function () {
var images = [
{src:'bilder/bild1.gif',delay:3000},
{src:'bilder/bild2.gif',delay:2000},
{src:'bilder/bild3.gif',delay:1500},
{src:'bilder/bild4.gif',delay:4000}
],
element = document.images['wechsel'],
change_image = function () {
var image = images[ Math.floor( Math.random() * images.length ) ];
// (Math.random()*images.length)>>0 would be a lot faster
element.src = image.src;
setTimeout(change_image, image.delay);
};
setTimeout(change_image, 10000);
};
The delay would change based on the image you currently have.
This has a few speed improvements and the code is as simple as it can get.
This was untested!
Here is a (slightly) changed version to change the text color:
window.onload = function () {
var colors = [
{name:'red',delay:3000},
{name:'yellow',delay:1000},
{name:'green',delay:2300},
{name:'blue',delay:2600},
{name:'pink',delay:1300},
{name:'purple',delay:500},
],
element = document.getElementById('span'),
change_color = function () {
var color = colors[ ( Math.random() * colors.length )>>0 ];
element.style.color = color.name;
setTimeout(change_color, color.delay);
};
setTimeout(change_color, 2000);
};
<span id="span" style="background:black;font-family:sans-serif;font-size:20px;font-weight:bold;padding:10px;">I change color!</span>

Well, first off, there are many considerations here.
You first need to understand that you can have a multi-dimensional array consisting of a series of objects, instead of plain strings (which is what you have now).
I suggest you do some reading on this here: (take a look at Mozilla's Developer Network, or google for it).
Now, you cannot do that with an interval, because intervals happen at a preset, well, interval. You need a timeout - but timeouts happen only once.
You can see where this is going, right? So you need to call the timeout again once the previous timeout has finished - that goes to a concept of "callback" (google "javascript callbacks").
In any case, I've put up a very simple example for you in JSFiddle - it doesn't solve your problem 100%, because I think it would be cool if you'd put some thinking into how this all works, but this should get you at least something to work with (also on JSFiddle - http://jsfiddle.net/Nitrium/kyvbnxfv/)
imab = [];
imab[0] = {
image: 'bilder/bild1.gif',
time: 1000
}
imab[1] = {
image: 'bilder/bild2.gif',
time: 500
}
imab[2] = {
image: 'bilder/bild3.gif',
time: 2500
}
imab[3] = {
image: 'bilder/bild4.gif',
time: 100
}
function BildWechselB() {
var num = Math.random();
var ran = Math.floor((imab.length - 1) * num);
return imab[ran];
}
var interval;
function callBack (imageSrc) {
printImage(imageSrc);
clearInterval(interval);
var newRandomImage = BildWechselB();
interval = window.setTimeout(callBack, newRandomImage.time, newRandomImage.image)
}
function printImage (src) {
var imageSrc = document.createTextNode(src);
var bodyTag = document.getElementsByTagName('body');
bodyTag[0].appendChild(imageSrc);
}
var firstRandomImage = BildWechselB();
interval = window.setTimeout(callBack, firstRandomImage.time, firstRandomImage.image);
Hope it helps!

Related

How can i change the contents of HTML dynamically

I have a Some messages to be displayed on every specific set of interval say 10 seconds.But at present i am able to show only one message .How to show rest of the messages after interval ..
Here is the Code..
<script type="text/javascript">
var v = "Your Text<br/>Hello";
var v2 = "Your Text2<br/>Hello2";
var v3 = "Your Text3<br/>Hello3";
window.setInterval(function () {
$("#dynamicMessage").html(v);
}, 10000);
</script>
As per my current code i am able to display the first message but how to show others like v2 ,v3 here.
Please help me..
Make an array with all your messages, and increase a counter inside the setInterval function.
You can take a look at the sample in this fiddle: http://jsfiddle.net/s6c4hs91/
var v = {};
v[0] = "Your Text<br/>Hello";
v[1] = "Your Text2<br/>Hello2";
v[2] = "Your Text3<br/>Hello3";
var i = 0;
window.setInterval(function () {
$("#dynamicMessage").html(v[i]);
if (i == 2) {
i = 0;
} else {
i = i + 1;
}
}, 500);
You should control how you want the messages to appear after you get to the end of the array of messages: I have done a loop to start with the first message.
For doing the fade in/out transition just add those functions arounfd the html "write" sentence:
$("#dynamicMessage").fadeOut(800,'swing',$("#dynamicMessage").html(v[i]).fadeIn(100));
view sample in: http://jsfiddle.net/s6c4hs91/1/
For more info. on fade in take a look at: http://www.w3schools.com/jquery/eff_fadein.asp
Try this : you can use array instead of three different variables and iterate through array after every 10 seconds.
<script type="text/javascript">
var v = ["Your Text<br/>Hello","Your Text2<br/>Hello2","Your Text3<br/>Hello3"];
var i = 0;
window.setInterval(function () {
$("#dynamicMessage").html(v[i]);
i++;
if(i==3)
i=0;
}, 10000);
</script>
DEMO
try it :
var messages = ["Your Text<br/>Hello","Your Text2<br/>Hello2","Your Text3<br/>Hello3"];
var index = 0;
window.setInterval(function () {
index /=3;
$("#dynamicMessage").html(messages[index]);
}, 10000);

Simple JavaScript image rotator

I have a simple image rotator on a website consisting of 4 images that have to appear for a few seconds before showing the next one. It seems to work on its first cycle but then when it gets back to the first image it doesn't show that one but works again from the second image and so on always missing that image on every cycle.
The function is called using onLoad EH in the body. In the body there is an img with my first image inside it. I'm a noob so please be gentle if I've missed anything out.
Here's what I have...
<body onLoad="sunSlideShow()">
<img src="IMAGES/slider1.gif" alt="slide-show" id="mySlider" width="900">
<body>
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0
function sunSlideShow()
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
i = 1;
setTimeout("sunSlideShow()", 3000);
}
sunSlideShow()
Change it to this:
else
i = 0;
setTimeout("sunSlideShow()", 3000);
Further to my other answer (which was wrong!)... Try this:
http://jsfiddle.net/pq6Gm/13/
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(sunSlideShow,3000);
});
var quotes = [
"http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2007/07/11/sun128.jpg",
"http://icons.iconarchive.com/icons/robinweatherall/seasonal/128/sun-icon.png",
"http://www.astronomytoday.com/images/sun3.gif",
"http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png"
];
var i = 0;
function sunSlideShow() {
document.getElementById("mySlider").src = quotes[i];
if (i < (quotes.length-1))
{
i++;
}
else
{
i = 0;
}
}
</script>
<body>
<img src="http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png" id="mySlider"/>
</body>
==================================================================
EDIT: This is wrong... please find my other answer on this page.
==================================================================
To start with, I wouldn't use ... you're better off starting the script with jquery once the page is loaded.
Add this to your head section:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
</script>
That will fire the sunSlideShow function once the page is loaded.
Then, you're starting your slideshow with var i = 0... but when you've got to the fourth image, you're setting it to 1?
I would be tempted to use a while loop to achieve what you want.
Something like this:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0;
function sunSlideShow(){
while (i<4)
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
{
i = 0;
}
sleep(3000);
}
}
function sleep(miliseconds){
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()){}
}
</script>
This script hasn't been tested... but it should start the sunSlideShow function once the page has loaded and then change the image every 3 seconds.
I too searched the web trying to find a general solution to the problem of rotating an image about its center. I came up with my own solution which works perfectly. The basic concept is simple: rotate the entire context by the desired angle (here called 'tilt'); calculate the image's coordinates in the NEW coordinate system; draw the image; lastly, rotate the context back to its original position. Here's the code:
var xp = rocketX * Math.cos(tilt) - rocketY * Math.sin(tilt);
var yp = rocketX * Math.sin(tilt) + rocketY * Math.cos(tilt);
var a = rocketX - xp;
var c = Math.sqrt(a*a + (rocketY-yp)*(rocketY-yp));
var beta = Math.acos(a/c);
var ap = c * Math.cos(tilt + beta);
var bp = c * Math.sin(tilt + beta);
var newX = rocketX + ap;
var newY = rocketY - bp;
context.rotate(tilt);
context.drawImage(littleRocketImage, newX-9, newY-40);
context.rotate(-tilt);
In the penultimate line, the constants '9' and '40' are half the size of the image; this insures that the rotated image is placed such that its center coincides with the center of the original image.
One warning: I use this only for first quadrant rotations; you'll have to put in the standard tests for the other quadrants that change the signs of the components.
Update: 2021
You can use the light-weight library Ad-rotator.js to setup simple Ad-rotation like this -
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>
<script>
const instance = rotator(
document.getElementById('myelement'), // a DOM element
[ // array of ads
{ url: 'https://site1.com', img: 'https://example/picture1.jpg' },
{ url: 'https://site2.com', img: 'https://example/picture1/picture2.jpg'},
// ...
]
);
</script>
<body onLoad="instance.start()">
<div id="myelement"></div>
<body>
Reference Tutorial

showing random value in div element with javascript

I want my div element to work like a timer and shows random numbers with an interval of 1s. http://jsfiddle.net/NHAvS/46/. That is my code:
var arrData = [];
for (i=0;i<1000;i++)
{
arrData.push({"bandwidth":Math.floor(Math.random() * 100)});
}
var div = document.getElementById('wrapper').innerHTML =arrData;
document.getElementById('wrapper').style.left = '200px';
document.getElementById('wrapper').style.top = '100px';
but the problem is that it only shows 1 data at a time. any idea how to fix it?
Thanks
Do this:
setInterval(myfun,1000);
var div = document.getElementById('wrapper');
function myfun(){
div.innerHTML ='bandwidth :'+Math.floor(Math.random() * 100);
}
Take a Look: http://jsfiddle.net/techsin/NHAvS/49/
Note: your example was messed up as on left side it was set to load in head which means your div would be undefined every time your script loads before your dom. so setting it to onload make it works little more. :D
Note: also you seem to be chaining functions as in jquery, but in javascript you don't do that. The functions are made to do that. i.e. div= ..getElementById..innerHtml='balbla'; would set div = bla... not element.
You're better off using jQuery and CSS to achieve your desired result. jQuery to find the element and to display the random number; and CSS instead of manually setting the position. (Obviously jQuery is just a personal choice and document.getElementById will suffice - but if you're planning on manipulating the DOM a lot, jQuery is probably a better route to take). See updated fiddle
$(function () {
var arrData = [];
for (i = 0; i < 1000; i++) {
arrData.push({
"bandwidth": Math.floor(Math.random() * 100)
});
}
var index = 0;
setInterval(function(){
$("#wrapper").text(arrData[index].bandwidth);
index++;
}, 1000);
});
You can do it like this:
var delay = 1000, // 1000 ms = 1 sec
i;
setTimeout(function() {
document.getElementById('wrapper').innerHTML = arrData[i];
i++;
}, delay);

jQuery slider - last to first transition

I created this slider (didn't want to use plugins):
function slider(sel, intr, i) {
var _slider = this;
this.ind = i;
this.selector = sel;
this.slide = [];
this.slide_active = 0;
this.amount;
this.selector.children().each(function (i) {
_slider.slide[i] = $(this);
$(this).hide();
})
this.run();
}
slider.prototype.run = function () {
var _s = this;
this.slide[this.slide_active].show();
setTimeout(function () {
_s.slide[_s.slide_active].hide()
_s.slide_active++;
_s.run();
}, interval);
}
var slides = [];
var interval = 1000
$('.slider').each(function (i) {
slides[i] = new slider($(this), interval, i);
})
The problem I have is that I don´t know how to get it after the last slide(image), it goes back to the first slide again. Right now, it just .hide and .show till the end and if there is no image it just doesn´t start again.
Can someone help me out with a code suggestion to make it take the .length of the slider(the number of images on it) and if it is the last slide(image), then goes back to the first slide(image)... like a cycle.
Edit: Slider markup
<div class="small_box top_right slider">
<img class="fittobox" src="img/home10.jpg" alt="home10" width="854" height="592">
<img class="fittobox" src="img/home3.jpg" alt="home3" width="435" height="392">
<img class="fittobox" src="img/home4.jpg" alt="home4" width="435" height="392">
</div>
Created a fixed version for you here.
The easiest way to do this is to run a simple maths operation where you currently have
_s.slide_active++;
Instead, I get _s.slide_active, add 1, then run that through modulus (%) to the total length — which gives the remainder:
_s.slide_active = (_s.slide_active + 1) % _s.slide.length;
Take a look at this Fiddle link, this will help you create the slider in a cyclic way.If the slider reaches the last image it will start again from the first image.
var index = $selector.index();
if (index == (length - 1)) {
$('img').first().removeClass('invisible').addClass('visible');
}
I hope this will help you more. All the best.
You need to get to 0 after length-1.
One simple way to do that is to work modulo length:
_s.slide_active++;
_s.slide_active %= length;
not tested but hope helpful :
function slider(sel, intr , i){
...
this.count = this.selector.children().length;
this.run();
}
slider.prototype.run = function(){
var _s = this;
this.slide[this.slide_active].show();
setTimeout(function(){
_s.slide[_s.slide_active].hide()
if(_s.slide_active == this.count)
_s.slide_active = 0;
else
_s.slide_active++;
_s.run();
}, interval);
}

random image; without repeating?

First off I'm not very familiar with javascript, thus here I am.
I have this code for my site to draw a random image. Working from this, how can I make the images not repeat? Thanks in adv! Code:
<script type="text/javascript">
var banner_list = ['http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/LM_LogoMark4-4-2.gif', 'http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/logobg_dome.png', 'http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/logobg_brain.png']; $(document).ready(function() { var ran = Math.floor(Math.random()*banner_list.length);
$(".logobg img").attr(banner_list[ran]);
}); $(document).bind("projectLoadComplete", function(e, pid){
var ran = Math.floor(Math.random()*banner_list.length);
$(".logobg img").attr("src", banner_list[ran]);
}); </script>
After you display the image splice it out of the array, you can use banner_list.splice(ran, 1);. The arguments are .splice(index, howManyToRemove, howManyToInsert). Inserting is optional, so you can just use splice to start at the index of the image you're displaying and remove one. Make sure not to remove it until you're done referencing it.
You can use Array.splice() as Robert suggest with 2 Arrays. One for unsused and one for used images. Check my JSfiddle.
var images = ["http://www.fowkesauto.com/products_pictures/nutsbolt.jpg",
"http://i01.i.aliimg.com/photo/v0/114511763/Fasteners_Bolts_and_Nuts.jpg",
"http://us.123rf.com/400wm/400/400/DLeonis/DLeonis0810/DLeonis081000018/3706757-bolts-and-nuts-on-white.jpg",
"http://static3.depositphotos.com/1003288/173/i/950/depositphotos_1737203-Nuts-and-bolts.jpg"],
usedImages = [];
setInterval(function () {changeImage();},500);
var changeImage = function () {
var index = Math.floor(Math.random() * (images.length)),
thisImage = images[index];
usedImages.push(thisImage);
images.splice(index, 1);
if (images.length < 1) {
images = usedImages.splice(0, usedImages.length);
}
$("#image").attr("src", thisImage);
}

Categories