tags:

views:

83

answers:

7

Hi,

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.

A: 

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.

Jason McCreary
+1  A: 

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>
Ben Rowe
WRONG. becomes funny after the 10000. iframe.src = undefined.... :) now it is a sequence not a rotation...
galambalazs
@galambalazs sorry I missed that.
Ben Rowe
thanks Ben but unfortunately it doesn't seem to be rotating through the URLS, just does the first one only?
tonsils
FYI, I am using IE6 and I believe it's not working b/c of this.
tonsils
A: 
<iframe id="rotator" src="http://...first"&gt;&lt;/iframe&gt;

<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>
galambalazs
"WRONG". `The requested URL /t/undefined was not found on this server.` because `urls.length` needs to be `urls.length-1`
meder
:)) thx. No, what I wanted is to start from 1, and increment index after changing the src. It works now.
galambalazs
A: 
<!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>
meder
arguments.callee is no longer part of the language. function 'f' is useless.
galambalazs
those are minor and subjective points compared to your broken script :) see my comment.
meder
A: 

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>
naikus
you are polluting the global namespace. bad practice :(
galambalazs
This example shows how it could be done. I never said its perfect. I expect the person asking the question would integrate this the way he/she sees fit and not take the code as it is. But thanks for the review anyway, I'll have namespaced objects and functions hereon. I think it should be a habit, no matter what you are coding :)
naikus
great attitude. :)
galambalazs
A: 

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.

Nick
A: 

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.

Thqr