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.
Related
I've been trying to set up a website that plays a random .webm that loops, then when you press a key, it plays the next random .webm. I got the random part down, but I can't seem to figure out how to get it to wait for the keystroke. Another issue I'm having is that I can't figure out how to get it to load a random .webm when the site is first visited. It just plays the first video (1.webm) I'm sorry if this is a bad question, I'm very new to web development.
I tried to make it so that when the key is pressed it would load a new .webm, but it didn't work.
Here's what I have:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>webm haha</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<video controls loop id="video1" src="data/1.webm" autoplay></video>
<script type="text/javascript" src="lib/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="lib/dat.gui.min.js"></script>
<script type="text/javascript" src="app_nue.js"></script>
</body>
</html>
JS:
var pGetRand;
var getRand;
//Settings
var settings = {
changeThresh : 0.1,
totalClips : 7,
pathToClips : "data/",
pbRate : 1,
mode : 'non-repeating-rand',
}
//Storage
var video1 = $('#video1');
var video2 = $('#video2');
var v1d,v2d,v1ct,v2ct;
var linearTracker = 1;
var gate1 = true;
var gate2 = false;
function toggle(element, pElement){
//start playing before the clip comes to the front.
element.get(0).play();
setTimeout(function(){
element.css('z-index', '500');
pElement.css('z-index', '0');
if(settings.mode == 'random'){
getRand = Math.floor( Math.random() * settings.totalClips +1 )
}
if(settings.mode == 'linear'){
if(linearTracker >= settings.totalClips){
linearTracker = 1;
}else{
linearTracker ++
}
getRand = linearTracker
console.log(linearTracker);
}
if(settings.mode == 'non-repeating-rand'){
getRand = Math.floor( Math.random() * settings.totalClips +1 )
while(getRand == pGetRand){ //are we the same, if so try again until we are not.
console.log("try again",getRand,pGetRand);
getRand = Math.floor( Math.random() * settings.totalClips +1 )
}
pGetRand = getRand
}
pElement.attr({ 'src': settings.pathToClips + getRand + '.webm' });
pElement.get(0).pause();
}, 150)
}
First off, you can use window.addEventListener to run a function on a keypress. The parameter key here has a property that says the id number of the key pressed. You can change that number to change what key needs to be pressed to change the video. You can read more on it here
window.addEventListener('keypress', function(key) {
//32 is the space key, use console.log(key.which)
to figure out the id for the key you want to use
if (key.which == 32) {
toggle();
}
});
In the overall function, you should be changing only the src of the video instead of hiding and showing a whole new element. At the begginning of the function, you would simply add this:
var element = document.getElementById("video1");
var vid = '1';//Backup
And at the end of the toggle function you would reset the time and change the src:
element.play();
element.currentTime = 0;
element.setAttribute('src', settings.pathToClips+vid+'.webm');
For your random function, you probably won't want the last video played to be repeated, so you should use filter to check if the new video id is the same as the last video played.
You can learn more about filter here
if (settings.mode == 'random') {
function getNewNumber() {
var lastVid = usedVids[usedVids.length-1];
if (lastVid == undefined || isNaN(lastVid)) {
lastVid = settings.totalClips+1;
//Makes sure there is no way the new vid could be the same
}
var vidNum = Math.floor(Math.random() * settings.totalClips) + 1;
var isUsed = usedVids.filter(a => a == vidNum);
//This makes sure that the video isn't the same as the last video (It helps make it seem more random)
if (isUsed[0] != lastVid) {
vid = vidNum;
usedVids = [vidNum];
}
else {
getNewNumber();
}
}
getNewNumber();
}
For linear, you just increase the variable for what vid you're on and set the video number to that.
if (settings.mode == 'linear') {
currentVidNum++;
if (currentVidNum > settings.totalClips) {
//This resets currentVidNum once it is at the max vids
currentVidNum = 1;
}
vid = currentVidNum;
}
Non-repeating-random is a bit trickier, but you can pull it off with a similar technique as random, except you don't remove all the values from the array of what you've played every time you update the video:
if (settings.mode == 'non-repeating-rand') {
var wasReset = false;
if (usedVids.length >= settings.totalClips) {
//This resets usedVids while still keeping the last video used so it won't play it again
var lastVid = usedVids[usedVids.length-1];
wasReset = true;
usedVids = [lastVid];
}
function getNewNumber() {
var newVidNum = Math.floor(Math.random() * settings.totalClips) + 1;
var isUsed = usedVids.filter(a => a == newVidNum);
if (isUsed[0] != newVidNum) {
if (wasReset == true) {
usedVids = [];
}
usedVids.push(newVidNum);
vid = newVidNum;
}
else {
getNewNumber();
}
}
getNewNumber();
}
To fix your problem of it not automatically setting a random video, you just need to call the toggle function at the end of the script.
I don't know if this was a good enough explanation so if it helps here's a snippet of the full code: (Although it won't work unless you have the videos :/)
window.addEventListener('keydown', function(key) {
if (key.which == 32) {
toggleVid();
}
});
//Settings
var settings = {
changeThresh: 0.1,
totalClips: 6,
pathToClips: "data/",
pbRate: 1,
mode: 'non-repeating-rand',
}
var currentVidNum = 1;
var usedVids = []; //Used for non-repeating-rand and random
function toggleVid() {
var element = document.getElementById("video1");
var vid = '1'; //Backup
if (settings.mode == 'random') {
function getNewNumber() {
var lastVid = usedVids[usedVids.length - 1];
if (lastVid == undefined || isNaN(lastVid)) {
lastVid = settings.totalClips + 1;
//Makes sure there is no way the new vid could be the same
}
var vidNum = Math.floor(Math.random() * settings.totalClips) + 1;
var isUsed = usedVids.filter(a => a == vidNum);
//This makes sure that the video isn't the same as the last video (It helps make it seem more random)
if (isUsed[0] != lastVid) {
vid = vidNum;
usedVids = [vidNum];
} else {
getNewNumber();
}
}
getNewNumber();
}
if (settings.mode == 'linear') {
currentVidNum++;
if (currentVidNum > settings.totalClips) {
currentVidNum = 1;
}
vid = currentVidNum;
}
if (settings.mode == 'non-repeating-rand') {
var wasReset = false;
if (usedVids.length >= settings.totalClips) {
var lastVid = usedVids[usedVids.length - 1];
wasReset = true;
usedVids = [lastVid];
}
function getNewNumber() {
var newVidNum = Math.floor(Math.random() * settings.totalClips) + 1;
var isUsed = usedVids.filter(a => a == newVidNum);
if (isUsed[0] != newVidNum) {
if (wasReset == true) {
usedVids = [];
}
usedVids.push(newVidNum);
vid = newVidNum;
} else {
getNewNumber();
}
}
getNewNumber();
}
element.play();
element.currentTime = 0;
element.setAttribute('src', settings.pathToClips + vid + '.webm');
}
<video controls loop id="video1" src="data/1.webm" autoplay='true'></video>
For the waiting keystroke issue, you may refer to this webpage.
For the random issue, you may refer to this web page.
I would like to have a simple picture slider. That slider should be in the header of the website and should switch between a small delay. I want it simple and named the pictures 1.jpg, 2.jpg and so on and they are in the folder "bilder".
I have tried a bit and here is my result:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript">
function picture_slider(){
setInterval( switch_picture(), 3000 );
return false;
}
function switch_picture() {
for ( var i = 1; i < 7 ; i++ ) {
var pfad = "bilder/" + i + ".jpg";
document.getElementById("bild").src = pfad;
i++;
};
return false;
}
</script>
</head>
<body onload="picture_slider();">
<img id="bild" src="" />
</body>
</html>
I guess, that I did something wrong, because my browser is showing only one picture and is not switching.
jsBin demo
On every loop you're iterating (for loop) over all your images, resulting in the latest one. Also use only switch_picture (instead of switch_picture()).
P.S: create an 0.jpg image for this counter:
function picture_slider(){
setInterval( switch_picture, 2000 ); // corrected removing "()"
}
var bild = document.getElementById("bild")
var i = 0; // Start from image 0.jpg
function switch_picture() { // don't iterate a loop in here!
bild.src = "bilder/"+ (i++ % 7) +".jpg";
}
I found something here: Stackoverflow Link
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript">
var i = 0;
var images = [ "1", "2", "3", "4", "5", "6", "7"]
function picture_slider(){
setInterval( switch_picture, 2000 );
}
function switch_picture() {
i++;
if ( i >= images.length ) {
i = 0;
};
var bild = document.getElementById("bild");
bild.src = "bilder/" + images[i] + ".jpg";
}
</script>
</head>
<body onload="picture_slider();">
<img id="bild" src="" />
</body>
</html>
// 1. images need to store in an Array
const images = [
"img/pic-1.jpg",
"img/pic-2.jpg",
"img/pic-3.jpg",
"img/pic-4.jpg",
"img/pic-5.jpg",
"img/pic-6.jpg",
"img/pic-7.jpg"
];
// 7. getElementById by calling, store globally (do not call inside loop/setInterval performance will loose)
const imgElement= document.getElementById("slider-image");
// 2. set initial value for array index
let imgIndex = 0;
// 3. create setInterval()
const sliderInterval = setInterval(() => {
// 6. check condition if length is finished then start again from 0
if (imgIndex >= images.length) { // use >= because index start from 0 and length start from 1, if use just > then last element will be undefined
imgIndex = 0;
}
// 5. testing
// console.log(imgIndex);
// 9. Dynamically change image src
const imgUrl = images[imgIndex];
imgElement.setAttribute('src', imgUrl);
// 4. increase value by 1
imgIndex++;
}, 1000);
I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});
I am currently making a web page with an image inside of a div tag. I wrote a script to change the image after a certain amount of time, and it works fine when I test the script alone, however; when I attempt to place the script within my web page, it does not change the image.
Here is the code for my script:
<!DOCTYPE html>
<html>
<body>
<script>
images = new Array;
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
setInterval( function() {
changeImage()
}, 5000);
x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if ( x < 8 ) {
x += 1;
} else if ( x = 9 ) {
x = 0;
}
}
</script>
<img id='ad' src="img.gif">
</body>
</html>
I have tested this script with the image inside of a div tag and it still works fine. When I put the same code into my web page, it does not work. Also note, the image file names are just examples. The images I am using are from photobucket, so I have very little control over what they are called. Any help I could get on this would be greatly appreciated.
You need to put your code inside window.onload = function() {}
var images = new Array();
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
function changeImage() {
document.getElementById('ad').src = images[x];
if (x<8) {
x+=1;
}
else if (x===9) {
x=0;
}
}
window.onload = function() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
Edit
This code has been tested on my local machine and works.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var images = new Array();
for (var i = 2; i < 11; i++) {
images.push("img" + i + ".gif");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
document.getElementById('imgsrc').innerHTML = "<h1>" + images[x] + "</h1>";
if (x < 8) {
x += 1;
} else {
x = 0;
}
}
window.onload = function() {
setInterval(function () {
changeImage();
}, 1000);
}
</script>
</head>
<body>
<img id="ad" src="img.gif" />
<div id="imgsrc"><h1>img.gif</h1></div>
</body>
</html>
Here is a fiddle of the final code working. JSFiddle doesn't like window.onload for some reason, so I had to exclude it. This doesn't really demonstrate my point, but I thought I'd just include it anyway.
Your code works to change the image src in this fiddle: http://jsfiddle.net/snB2a/1/
Try to rename your variables images and x to longer names. What can happen is, if some other code in your page, or worse, some code in one of the script file you page references, use variable "x" without declare it locally, then it would actually modify your "x" variable.
Here is an example to demonstrate the problem:
function something()
{
for (x = 0; i < 10; x++)
dosomethingelse();
}
If the above function is called in your page, then it will overwrite your "x" variable. The following code is safe:
function something()
{
var x;
for (x = 0; i < 10; x++)
dosomethingelse();
}
I have a Previous/Next link on my site that lets me go thru the images with this code:
Previous | Next
<span id='num'></span>
I have placed the images in the codes below. The Previous / Next links are working great but I would like to be able to click on the images itself to navigate to the next images: so click on 1.jpg then goes to 2.jpg so forth and once clicked on 5.jpg goes back to 1.jpg. Please advise, thanks in advance for your help. I am a beginner building my site blindly and any help is much appreciated.
<script type="text/javascript">
var image = new Array("jpegs/1.jpg",
"jpegs/2.jpg",
"jpegs/3.jpg",
"jpegs/4.jpg",
"jpegs/5.jpg"
)
var imgNumber=1
var numberOfImg = image.length
function previousImage(){
if(imgNumber > 1){
imgNumber--
}
else{
imgNumber = numberOfImg
}
document.slideImage.src = image[imgNumber-1]
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.slideImage.src = image[imgNumber-1]
}
</script>
How about:
document.slideImage.onclick = nextImage;
I would also suggest using event registration (also for the anchors):
document.slideImage.addEventListener('click', nextImage);
I wouldn't recommend using href="Javascript:function()", so to give you an idea of how to approach it...
<script type="text/javascript">
window.onload = function() {
var n = 0;
var src = ["jpegs/1.jpg", "jpegs/2.jpg", "jpegs/3.jpg", "jpegs/4.jpg", "jpegs/5.jpg"];
var e = document.getElementById('slideImage');
var prev = function() {
n -= 1;
if(n < 0) n = src.length - 1;
e.setAttribute('src', src[n]);
};
var next = function() {
n += 1;
if(n >= src.length) n = 0;
e.setAttribute('src', src[n]);
};
e.onclick = next;
document.getElementById('nextlink').onclick = next;
document.getElementById('prevlink').onclick = prev;
};
</script>
This method does not write variables to window (excluding onload) and only requires an id attribute.