userBG
userBG

Reputation: 7180

How to navigate through an array of urls as list of links and with previous/next links?

I have an array of urls that I want to display one by one in an iframe. The user will navigate to each URL by clicking a link in a list of the URLs or by clicking the previous/next links. What is the best way to do this? Working code snippets would be very very appreciated.

I'm posting as few details as possible below for best clarity.

var urls = [{"name":"ebay","url":"http://ebay.com"},
{"name":"amazon","url":"http://amazon.com"},
{"name":"msn","url":"http://msn.com"},
{"name":"yahoo","url":"http://yahoo.com"},
{"name":"wikipedia","url":"http://wikipedia.org"}];

List of links (alternate way to navigate instead of prev/next links below)

<ol id="list">
  <li><a href="" target="myframe">ebay</a></li>
  <li><a href="" target="myframe">amazon</a></li>
  <li><a href="" target="myframe">msn</a></li>
  <li><a href="" target="myframe">yahoo</a></li>
  <li><a href="" target="myframe">wikipedia</a></li>
</ol>

currently viewing: <span id="current"></span>

prev: <a href="" target="myframe"></a> | next: <a href="" target="myframe"></a>

//all the links will open inside this iframe using target="myframe"
<iframe src="" name="myframe" id="myframe"></iframe>

Upvotes: 1

Views: 3610

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83366

Give your next and previous links ids

prev: <a href="" id="prev" target="myframe"></a> | next: <a id="next" href="" target="myframe"></a>

Then some basic script should wire this up

var currentIndex = 0;
function next(){
    if (currentIndex != Urls.length - 1)
        load(urls[++currentIndex].url);
}

function previous(){
    if (currentIndex != 0)
        load(urls[--currentIndex].url);
}

function() load(url){
    $("#myframe").attr("src", url);
}

$(function() {
    $("#prev").click(function() { previous(); });
    $("#next").click(function() { next(); });
});

To handle the explicit links, I'd use data attributes to store the url, and use the same load function:

<ol id="list">
  <li><a href="#" data-url="www.ebay.com" >ebay</a></li>
  <li><a href="#" data-url="www.amazon.com" >amazon</a></li>
  <li><a href="#" data-url="..." >msn</a></li>
  <li><a href="#" data-url="..." >yahoo</a></li>
  <li><a href="#" data-url="..." >wikipedia</a></li>
</ol>

Then inside that jQuery document load function, something like:

$("#list a").click(function() { load($(this).data("url")); });

So the whole thing would look like:

$(function() {
    $("#prev").click(function() { previous(); });
    $("#next").click(function() { next(); });
    $("#list a").click(function() { load($(this).data("url")); });
});

Upvotes: 1

Related Questions