Smooth div “gallery” with jQuery tabs
I'm looking for an elegant and efficient solution for something that can be described as a div
“gallery”.
Currently we're using jQuery UI tabs and prepopulate div
s on server. The user only sees the active div
and can move to next or previous tab. However, as the list now contains more than 100 items, we would like to switch to a dynamic loading approach.
At first, I tried to separate div
generation for an item to an AJAX call, and use builtin Tabs AJAX functionality. However, the glitch when moving back or forth with jQuery UI Tabs AJAX is very noticeable. When the tab has loaded, it gets cached so it works normal again.
I have the following ideas now:
Somehow prefetch next 5 tabs each time user clicks 'Next'.
The user isn't likely to scroll very fast, and we're okay with glitches in case of fast scrolling. All I want to do is to ensure that normally several next tabs are loaded before they get displayed. Is this possible with jQuery Tabs?
Populate a JavaScript array on server and create
div
s on the fly.This is another possible solution I'm looking into. I could've written a function to generate
div
by object data saved in JavaScript. The JavaScript could be generated by server.
Which is more appropriate开发者_开发技巧? Am I missing something?
Okay, so as I got no responses I went with the second route and it seems like a good solution.
A script in the head
section populates globally visible items
data list with JSON generated in-place by server.
Then, where tabs div
s were previously defined, I put a script to generate them on-the-fly:
<div id="tabs" class="ui-tabs">
<ul class="ui-tabs-nav"></ul>
<script type="text/javascript">
for (var i = 0; i < items.length; i++)
createTab(items[i], i);
</script>
</div>
createTab
function is defined in a separate JS file and manages creating div
and list items for ul
:
function createTab(item, index) {
createPanel(item, index).appendTo($('#tabs'));
createTabItem(index).appendTo($('.ui-tabs-nav'));
}
// creates list item with a href="#tabs-1..n"
function createTabItem(index) {
return $('<li></li>').append(
$('<a></a>').attr('href', '#tabs-' + (index+1))
);
}
// creates a div for tab
function createPanel(item, index) {
var panel = $('<div class="ui-tabs-panel"></div>')
.attr('id', 'tabs-'+ (index+1)); // id = "tabs-1..n"
if (index > 0) panel.addClass('ui-tabs-hide'); // hide all tabs but the first
// whatever you need to fill the tab with
createPicture(item).appendTo(panel);
createDescription(item).appendTo(panel);
return panel;
}
Since all of this happens before the page is loaded, I didn't have to change the code that manages tab navigation.
Of course, this doesn't yet enable prefetching images, but makes it much easier to do, as tab creation occurs at one place and it's become easier to control.
精彩评论