I'm making a full-screen slider with maximage & cycle that (so far) does the following:
- Compares a given URL hash against each slide's ID and loads a match, if found,
- Appends the first slide's ID to the address bar as a hash, if none is specified,
- Replaces, rather than appends, a history entry when browsing through the slides, as well as updating the location hash.
Here's the main bulk of code...
jQ(function(){
// Globals
var s,
slideIDs = {};
// Populate slides object
jQ('#slides').children('div').each(function(i) {
s = jQ(this).attr('id').replace(/\ /g, '-');
slideIDs[s] = i;
});
// Find slide via hash, go to first if !valid
function getSlide(){
if ( slideIDs[window.location.hash.substring(1)] >= 0 ) {
var nxtSlide = slideIDs[window.location.hash.substring(1)];
return nxtSlide;
} else {
return 0;
}
};
// Post-slide hash handling
(function(namespace) { // Closure to protect local variable "var hash"
if ('replaceState' in history) { // html5 support
namespace.replaceHash = function(newhash) {
if ((''+newhash).charAt(0) !== '#') newhash = '#' + newhash;
history.replaceState('', '', newhash);
}
} else {
var hash = location.hash;
namespace.replaceHash = function(newhash) {
if (location.hash !== hash) history.back();
location.hash = newhash;
};
}
})(window);
...the maximage/cycle part...
jQ('#slides').maximage({
cycleOptions: {
startingSlide: index,
cssTransitions: true,
after: onAfter,
fx: 'fade',
speed: 210,
timeout: 0,
},
});
function onAfter(el, next_el, opts) {
jQ(el).removeClass('active');
jQ(next_el).addClass('active');
var nextHash = jQ(next_el).find('.slideLink').text().toLowerCase().replace(/\ /g, '-');
window.replaceHash(nextHash);
};
...and finally the hashchange part...
jQ(window).bind('hashchange', function() {
var nextSlide = getSlide();
jQ('#slides').cycle(nextSlide);
})
});
It's working well, apart from a couple of issues:
In HTML4 browsers - if a hash is not specified - on page load, the first slide's ID will be added to the hash, but an unwanted extra history entry is also created,
And when the hash is manually changed, the slides transition without reloading the page, but a new history entry is created again.
I've a feeling I'm close, but I can't figure it out. Does anyone have any ideas as to how I could overcome these?