• 0

How should I do this?


Question

I've been trying to do this for some time and have failed so I want to see how other people would do it.

I'm trying to create a tab interface. Each tab object has a .src property and when it is clicked it will load that property (as a string of course) into an iframe. This part I have got to work so there's no problem here.

The difficulty I'm having is with changing the property. When a user moves about inside the iframe I want the property to update accordingly so that when the tab is clicked again it will start where the user left off.

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

When the user switches the tab, you could first retrieve the values of scrollX and scrollY on the iframe's window object through its contentWindow property. You can store these values in some cache object and use scrollTo to scroll to the saved position.

// Example of cache object layout
var scrollCache = {
   "http://foo.bar/page1.html" : [ 12, 34 ],
   "http://foo.bar/page2.html" : [ 56, 78 ]
};

// Save (before switching)
var iframe = document.getElementById("tabframe");
scrollCache[iframe.src] = [ iframe.contentWindow.scrollX, iframe.contentWindow.scrollY ];

// Restore (after loading)
var iframe = document.getElementById("tabframe");
var scrollPos = scrollCache[iframe.src] || [0,0];
iframe.contentWindow.scrollTo( scrollPos[0], scrollPos[1] );

You declare scrollCache as an empty object at the top of your script and before switching the tab, you save the position and assign it the current page URL as key. Afterwards, when the new tab is done loading (use the load event for this), you retrieve the saved position from the object and use scrollTo using these values.

Although this might work out for you, I suggest you to stay far away from framesets and iframes. These days, such tab interfaces are done using AJAX which gives you much more flexibility and enhances the user experience. Have a look at jQuery UI's Tabs component.

When you style the tabs widget so that .ui-tabs-panel has a fixed height and overflow set to auto, scrollbars will appear when needed and since all panels are independent, their scroll position will be retained. From there, you're in total control of your tabs thanks to the awesomeness of jQuery. :p

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.