0

I have an array of URLs, for example:

var urls = ["http://www.getbootstrap.com","http://www.reddit.com","http://www.bbc.com/news","http://www.google.com"];

and I have an iframe:

<iframe></iframe>

and two links:

<a href="#" id="forwards">Forwards</a> <a href="#" id="backwards">Backwards</a>

What I am trying to do is link it up so that the <iframe> shows the first URL in the array, and when you click either forwards or backwards it changes the src attribute to either the next url or the previous url. Also, when it is at the begining or end of the array then clicking the buttons should take it to the end or begining of the array, respectivly. I have this:

$('#forwards').click(function(){
    current++;
    $('iframe')[0].src = urls[current];
});

and the same to go backwards, but it is very inefficient, and doesn't work when you get to either end of the array. Is there a better way to do it?

4
  • Without quotes, it's expecting iframe to be a variable Commented Dec 1, 2013 at 5:59
  • Whoops, my bad, I missed the quotes when typing it out Commented Dec 1, 2013 at 6:02
  • shouldn't it be $('#forwards').click()? Commented Dec 1, 2013 at 6:04
  • Yeah, it should. I was typing up the code in the questions by hand rather than copying and pasting because other stuff is going on so that is a simpler version. Commented Dec 1, 2013 at 6:06

1 Answer 1

2

DEMO

var urls = ["http://www.getbootstrap.com",
            "http://www.reddit.com",
            "http://www.bbc.com/news",
            "http://www.google.com"
           ],
    c = 0,
    n = urls.length;

$('#forwards, #backwards').click(function( e ){
    e.preventDefault(); 
    c = this.id=='forwards' ? ++c : --c;
    c = c<0? n-1 : c%n ;

    $('iframe')[0].src = urls[c];
}); 

n.b. Google uses X-Frame-Options header to prevent it's service to be embedded into an iframe inside an external page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.