Javascript Change Image on Timer - javascript

I'm trying to rotate a set of 6 images in javascript, not jquery. The first image shows up, but the rest of them don't rotate. Here's my code:
<html>
<head>
<script type="text/javascript">
function rotatePic() {
var qutAd = document.getElementById("yumOreos");
var imgs = ["images/img1.png", "images/img2.png", "images/img3.png", "images/img4.png", "images/img5.png", "images/img6.png"];
var ad = 0;
qutAd.src = imgs[ad];
setInterval(function () {ad++;if (ad == imgs.length) {ad = 0;}}, 4000);
}
</script>
</head>
<body onload="rotatePic()">
<img id="yumOreos">
</body>
</html>
What am I doing wrong? Thanks.

You have to set the src in the interval function as well.
setInterval(function () {
ad++;
if (ad == imgs.length) ad = 0;
qutAd.src = imgs[ad];
}, 4000);

You have forgotten to change the index of the array, to change the source. So you can do this
setInterval(function () {if (ad == imgs.length) {ad = 0;} qutAd.src =imgs[ad++]}, 4000);
}

Related

Gradually show an image using Javascript with the CSS property opacity

I need some help with my code. The task is to show an image by using a button. But the image has to show gradually with the CSS property "opacity".
The image should start at opacity 0 and should end at opacity 1.
Our teacher suggests us using "parsefloat" so the strings from CSS could be recognized by JS as numbers.
I do not really know why my code is not working. I would really appreciate it if you could show me where my mistake is.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Aufgabe 12.2</title>
<script>
var go = function() {
var opac = function(delay) {
var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";
var level = 0;
var step = function(){
img.style.opacity = level;
if(level <= 1) {
level += .1;
setTimeout(step, delay);
}
}
step();
}
opac(100);
};
</script>
<body>
<input type = "button" onclick = "go();" value = "Click me"/>
</body>
</head>
</html>
your code almost works, the only problem is that after you create your img variable, you never append it to the document. You create the image and correctly make it fade in but it is not part of the document so it will not be rendered. To fix this, addIn this line, document grabs a reference to the whole HTML document, and .body references the body tag. The .appendChild tells it to add a child element, to the body.
Here is a working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Aufgabe 12.2</title>
<script>
var go = function () {
var opac = function (delay) {
var img = document.createElement('img');
img.src =
'http://www.google.com/intl/en_com/images/logo_plain.png';
document.body.appendChild(img);
var level = 0;
var step = function () {
img.style.opacity = level;
if (level <= 1) {
level += 0.1;
setTimeout(step, delay);
}
};
step();
};
opac(100);
};
</script>
<body>
<input type="button" onclick="go();" value="Click me" />
</body>
</head>
</html>
Here is a link with more information
You need to append the img node to the DOM:
const btn = document.querySelector("input")
btn.onclick = () => go(100)
var go = function(delay) {
var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";
document.body.append(img)
var level = 0;
const step = function() {
img.style.opacity = level;
if (level <= 1) {
level += .1;
setTimeout(step, delay);
}
}
step();
}
<input type="button" value="Click me" />

Second Timer with Jquery

i have a jquery function like the below, and display resualt in span but when reload page this span hide and show for for a while .
i want that not hide and show Is there a way to do this?
Because I use it as a timer.!!
<span id="timer"></span>
<script>
var counter = 61;
var x = setInterval(function () {
counter = counter-1;
$('#timer').html(counter);
},1000);
</script>
Start your timer from 60sec instead of 61.
var counter = 60;
$('#timer').html(counter);
var x = setInterval(function () {
counter = counter-1;
$('#timer').html(counter);
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>
Initialise your span with counter before setInterval.
Hope this will help you.
Initially your timer span is empty.
var counter = 61;
$('#timer').html(counter); // add this line
var x = setInterval(function () {
counter = counter-1;
$('#timer').html(counter);
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>
It is because you are setting the html after one sec. Before setInterval is triggered, there is nothing present in the span.
This is what you can do
var counter = 61;
const timer = $("#timer");
timer.html(counter);
var x = setInterval(function () {
counter = counter-1;
timer.html(counter);
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>
https://jsfiddle.net/vatsalpande/f1kytyhz/

Make JavaScript change background image every 5 seconds

I am trying to change my background image every 5 seconds. How should I go about this?
window.onload = function () {
function Timer() {
window.setInterval("changeImage()", 5000);
}
function changeImage() {
var BackgroundImg["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"];
var i = Math.floor((Math.random() * 3));
var bgImg = document.body.style.backgroundImage();
bgImg.url = BackgroundImg[i];
}
}
You can make few changes
1.Not sure from where you are calling Timer function (better if
have camelCase)
function Timer() {
window.setInterval("changeImage()", 5000);
}
Instead you can directly use
setInterval(changeImage, 5000);
changeImage is a callback
2.Could not make out what is this line mean
var bgImg = document.body.style.backgroundImage();
Unsure if can attach a function to style property.
Anyway this below snippet can be useful
window.onload = function () {
// Array of Images
var backgroundImg=["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBinSpWOvAtkxjmkf709O3rjH2ObRbWAEn9s0JcWaeL6LMtCbOrQ",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKY4J2qIFqkuDnABMzeypywbMSZL1cleS8vpySz0KD02wOYORU1g",
"https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQkdQT0zN0xDVP-VuvwojSbS5dOstX14eZvJCOWNPxKJ5dWTIc"
]
setInterval(changeImage, 5000);
function changeImage() {
var i = Math.floor((Math.random() * 3));
document.body.style.backgroundImage = "url('"+backgroundImg[i]+"')";
}
}
DEMO
you are accessing style incorrectly
window.onload = function () {
function changeImage() {
var BackgroundImg=["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"
];
var i = Math.floor((Math.random() * 4));
document.body.style.backgroundImage = 'url("' + BackgroundImg[i] + '")';
}
window.setInterval(changeImage, 5000);
}
Also, if possible (usually is) don't pass a string to window.setInterval - use as above
Here's a solution to your question. Hope it helps!
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function changeImage() {
setInterval(displayNextImage, 5000);
}
var images = [], x = -1;
images[0] = "http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg";
images[1] = "http://www.planwallpaper.com/static/images/background-gmail-google-images_FG2XwaO.jpg";
images[2] = "http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg";
</script>
</head>
<body onload = "changeImage()">
<img id="img" src="http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg"/>
</body>
</html>

javascript image slideshow works in all other browsers but not IE

I have an image slideshow which will work in any other browser I try but not in IE - it just does nothing but display the primary image. Please could someone tell me I not going mad and it is a simple fix that I can't see.
Many thanks
Mickeyjay.
Code below:
<div id="image_slide"><img src="images/.......jpg" id="slideit" name="slideit" border="0">
<script type="text/javascript">
var dimages=new Array();
var numImages=3;
dimages[0]=new Image();
dimages[0].src="images/.......jpg";
dimages[1]=new Image();
dimages[1].src="images/.......jpg";
dimages[2]=new Image();
dimages[2].src="images/.......jpg";
var curImage=-1;
function swapPicture()
{
if (document.images)
{
var nextImage=curImage+1;
if (nextImage>=numImages)
nextImage=0;
if (dimages[nextImage] && dimages[nextImage].complete)
{
var target=0;
if (document.images.slideit)
target=document.images.slideit;
if (document.all && document.getElementById("slideit"))
target=document.getElementById("slideit");
if (target)
{
target.src=dimages[nextImage].src;
curImage=nextImage;
}
setTimeout("swapPicture()", 1500);
}
else
{
setTimeout("swapPicture()", 150);
}
}
}
setTimeout("swapPicture()", 1500);
</script>
Try this simplified test, the idea is to load your pictures before start to swap, and will not need to test .complete that way.
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="image_slide"><img src="intro.jpg"
id="slideit" name="slideit" border="0"></div>
<script type="text/javascript">
var curImage = -1;
var numImages = 2;
var dimages = new Array();
function loadPictures()
{
dimages[0] = new Image();
dimages[0].src = "test1.jpg";
dimages[1] = new Image();
dimages[1].src = "test2.jpg";
setTimeout(swapPicture, 3000);
}
function swapPicture()
{
var nextImage = curImage + 1;
if (nextImage >= numImages)
nextImage = 0;
document.images.slideit.src = dimages[nextImage].src;
curImage = nextImage;
setTimeout(swapPicture, 1500);
}
setTimeout(loadPictures, 1500);
</script>
</body>
</html>

Rotating URLs within an Iframe

I have 10 different urls that I want to feed into an iframe src attribute that I would also like to rotate say every 5 seconds between all the 10 urls within the iframe.
Unsure how to do this using javascript/best approach?
Sorry, should've mentioned that I am using IE6.
Thanks.
<iframe id="rotator" src="http://...first"></iframe>
<script>
// start when the page is loaded
window.onload = function() {
var urls = [
"http://...first",
"http://...second",
// ....
"http://...tenth" // no ,!!
];
var index = 1;
var el = document.getElementById("rotator");
setTimeout(function rotate() {
if ( index === urls.length ) {
index = 0;
}
el.src = urls[index];
index = index + 1;
// continue rotating iframes
setTimeout(rotate, 5000);
}, 5000); // 5000ms = 5s
};
</script>
Javascript (place in window.onload)
var urls = ['http://www.stackoverflow.com', 'http://www.google.com'];
var pos = 0;
next();
setInterval(next, 5000); // every 5 seconds
function next()
{
if(pos == urls.length) pos = 0; // reset the counter
document.getElementById('rotate').src = urls[pos];
pos++;
}
HTML
<iframe id="rotate"></iframe>
There are many ways, so best is up for debate. Take a look at setInterval() since you mentioned JavaScript. I'd write a method that got the iframe on the page by it's id attribute, getElementById() and changed the src attribute to the next URL in the array of URLs.
<!doctype html>
<html>
<body>
<iframe id="foo"></iframe>
<script>
(function() {
var e = document.getElementById('foo'),
f = function( el, url ) {
el.src = url;
},
urls = [
'http://www.msn.com/',
'http://www.mtv.com/'
],
i = 0,
l = urls.length;
(function rotation() {
if ( i != l-1 ) {
i++
} else {
i = 0;
}
f( e, urls[i] );
setTimeout( arguments.callee, 5000 );
})();
})();
</script>
</body>
</html>
Is there a reason to reload the iframes every time they rotate in? I might load all the iframes upfront and simply rotate through their display if this particular project was concerned with quality of experience.
Hi I assume you would want to load the page completely before starting the timer to load the next URL, otherwise you would end up showing the next URL before the existing page even shows up (depending on your internet speed).
Secondly you said you want to rotate the URLS.
Below is the tested code for this:
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
var urls = [
"http://www.google.com"
,"http://www.yahoo.com"
,"http://www.ajaxian.com"
,"http://www.ebay.com"
];
function showUrl(idx) {
alert(idx + " Showing " + urls[idx]);
var f = document.getElementById("f");
// call the next load after 5 seconds only after
// this iframe loads
f.onload = function() {
var next = ++idx % urls.length;
setTimeout(function(){
showUrl(next);
}, 5000);
}
// set the src
f.src = urls[idx];
}
</script>
</head>
<body onload="showUrl(0)" class="app-chrome">
<iframe id="f" src="about:blank"></iframe>
</body>
</html>
Adding a more compact version: (Works in IE6, FF, Opera, Chromium)
<script type="text/javascript">
window.onload = (function(urls, interval) {
var idx = 0;
var bAttached = false;
return function showUrl() {
var f = document.getElementById("f");
var onLoad = function() { // loading only after previous page loads
idx = ++idx % urls.length; // rotation
setTimeout(showUrl, interval);
}
if(! bAttached) {
if(navigator.userAgent.indexOf("MSIE") !== -1) {
f.attachEvent("onload", onLoad);
bAttached = true;
}else {
f.onload = onLoad;
}
bAttached = true;
}
f.src = urls[idx];
};
})([
"http://www.google.com" ,"http://www.yahoo.com" ,
"http://www.sun.com" ,"http://www.ebay.com"
], 5000
);
</script>
I am not going to do it all for you but an example as requested:
Using Jquery for ease.
Code:
<script type="text/javascript">
//sets a var to 0//
var MyInt = 0
//sets some URLS//
var url1 = 'http://UR1L.com';
var url2 = 'http://URL2.com';
var url3 = 'http://URL3.com';
function RunEveryTenSecs {
// Increases var by 1//
MyInt + 1;
//Checks var value if 1 runs if not goes to next//
if (MyInt == 1) {
$('#MyElementID').html('<iframe src="' + url1+ '"></iframe>');
}
if (MyInt == 2) {
$('#MyElementID').html('<iframe src="' + url2+ '"></iframe>');
}
if (MyInt == 3) {
$('#MyElementID').html('<iframe src="' + url3+ '"></iframe>');
MyInt = 0;
}
}
window.setTimeout(RunEveryTenSecs, 10000);
</script>
HTML:
<div id="MyElementID">
IFRAME WILL GO HERE.
</div>
It may not be the neatest there are other ways to do it but it is something simple and easy to understand. The URL's dont have to be seperate but it will make changing them in the future easier.

Categories

Resources