Change URL hash on scroll and keep back button working - javascript

On a one page layout with fixed top menu and anchor navigation I have a "scrollspy" in place that changes the fragment identifier on scroll, gives the menu link an active class depending on scroll position and animates the scrolling to the anchor with Velocity.js.
Unfortunately what it also does, when clicking the browser back button it takes me through all the steps of the scrolled way, meaning I load the site and scroll down and up a tiny bit and then hit the back button frequently the browser will also scroll down and up but won't go to either the last visited id or back in browser history actually.
Here is the jsfiddle.
// jQuery on DOM ready
// In-Page Scroll Animation with VelocityJS
// ------------------------------------------------ //
// https://john-dugan.com/fixed-headers-with-hash-links/
$('.menu-a').on('click', function(e) {
var hash = this.hash,
$hash = $(hash)
addHash = function() {
window.location.hash = hash;
};
$hash.velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], complete: addHash });
e.preventDefault();
});
// ScrollSpy for Menu items and Fragment Identifier
// ------------------------------------------------ //
// https://jsfiddle.net/mekwall/up4nu/
$menuLink = $('.menu-a')
var lastId,
// Anchors corresponding to menu items
scrollItems = $menuLink.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+ 30; // or the value for the #navigation height
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
$menuLink
.parent().removeClass("active")
.end().filter("[href='#"+id+"']").parent().addClass("active");
}
// If supported by the browser we can also update the URL
// http://codepen.io/grayghostvisuals/pen/EtdwL
if (window.history && window.history.pushState) {
history.pushState("", document.title,'#'+id);
}
});
With the above code the following works fine:
The hash or fragment identifier updates fine when clicked on the menu link using VelocityJS for the scrolling animation.
The active class is given to the corresponding menu link on scrolling.
The fragment identifier also updates fine when scrolling instead of clicking the menu link.
Question
Part 1: When you scroll a tiny bit on the fiddle and then hit the back button you will see that the scrollbar "travels" the exact same way, remembering the scrolling that was done.
I need the back button to work like it normally does.
a) Either go back in browser history and return to the page/site you were on and
b) when having clicked an anchor link (i) and then anchor link (ii) and then the back button the page should go back to anchor link (i).
Part 2: Since history.pushState is not supported in IE8 I am looking for a way to use window.location.hash = $(this).attr('id'); instead. No matter what I have tried towards the end of the code I simply cannot get window.location.hash = $(this).attr('id'); to work. I don't really want to use HistoryJS or something for this but am interested to learn this and write it myself.
Apart from the back button broken behaviour all the other behaviour that I want is already there, now I just need to fix the back button behaviour.
edit
I think I might have found a solution here, will test and then reply in detail if I get this to work.
Related:
smooth scrolling and get back button with popState on Firefox - need to click twice
jQuery in page back button scrolling
Modifying document.location.hash without page scrolling
How to Detect Browser Back Button event - Cross Browser

To answer the first part of your question, if you don't want to pollute the browser's history, you can use history.replaceState() instead of history.pushState(). While pushState changes the URL and adds a new entry to the browser's history, replaceState changes the URL while modifying the current history entry instead of adding a new one.
There is also a good article including differences between pushState and replaceState on MDN.

For older browsers I decided to include https://github.com/devote/HTML5-History-API and with this in place I got the desired behaviour (more or less).
This answers has:
- a scroll spy for the menu items and sets and active class to those on scroll
- the scroll spy also works for the URL hash, setting the correct hash depending on the section that is currently scrolled to
- a scroll stop function that checks when the user has stopped scrolling and then takes the value form the currently active menu item and sets that as the current URL hash. This is done on purpose to not catch the sections' anchors while scrolling but only the anchor of the section that the user scrolls to.
- a smooth scroll with Velocity.js when clicking on the menu links as well as when using the back and forward buttons
- functions that reacts to loading and reloading the page, meaning if you enter the page with a specific URL hash for a section it will animate the scroll to that section and if the page is reloaded it will animate the scroll to the top of the current section
The code is a rough sketch and could possibly use a few tweaks, this is just for demo purpose. I think I am still a beginner to please point out obvious errors so that I can learn from those. All links to where code snippets come from are included as well.
// In-Page Scroll Animation to Menu Link on click
// ------------------------------------------------ //
// https://john-dugan.com/fixed-headers-with-hash-links/
// https://stackoverflow.com/questions/8355673/jquery-how-to-scroll-an-anchor-to-the-top-of-the-page-when-clicked
// http://stackoverflow.com/a/8579673/1010918
// $('a[href^="#"]').on('click', function(e) {
$('.menu-a').on('click', function(e) {
// default = make hash appear right after click
// not default = make hash appear after scrolling animation is finished
e.preventDefault();
var hash = this.hash,
$hash = $(hash)
$hash.velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], queue: false });
});
// In-Page Scroll Animation to Hash on Load and Reload
// ----------------------------------------------------------- //
// https://stackoverflow.com/questions/680785/on-window-location-hash-change
// hashchange triggers popstate !
$(window).on('load', function(e) {
var hash = window.location.hash;
console.log('hash on window load '+hash);
$hash = $(hash)
$hash.velocity("scroll", { duration: 500, easing: [ .4, .21, .35, 1 ], queue: false });
// if not URL hash is present = root, go to top of page on reload
if (!window.location.hash){
$('body').velocity("scroll", { duration: 500, easing: [ .4, .21, .35, 1 ], queue: false });
}
});
// In-Page Scroll Animation to Hash on Back or Forward Button
// ---------------------------------------------------------- //
$('.menu-a').on('click', function(e) {
e.preventDefault();
// keep the link in the browser history
// set this separately from scrolling animation so it works in IE8
history.pushState(null, null, this.href);
return false
});
$(window).on('popstate', function(e) {
// alert('popstate fired');
$('body').append('<div class="console1">popstate fired</div>');
$('.console1').delay(1000).fadeOut('slow');
if (!window.location.hash){
$('body').append('<div class="console2">no window location hash present</div>');
$('body').velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], queue: false });
$('.console2').delay(1000).fadeOut('slow');
}
console.log('window.location.hash = '+window.location.hash);
var hash = window.location.hash;
$hash = $(hash)
$hash.velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], queue: false });
});
// ScrollSpy for Menu items only - gives selected Menu items the active class
// ------------------------------------------------------------------------ //
// Does not update fragment identifier in URL https://en.wikipedia.org/wiki/Fragment_identifier
// https://jsfiddle.net/mekwall/up4nu/
var lastId,
// Anchors corresponding to menu items
scrollItems = $menuLink.map(function(){
var item = $($(this).attr("href"));
// console.table(item);
if (item.length) { return item; }
});
// Give menu item the active class on load of corresponding item
function scrollSpy () {
// Get container scroll position
var fromTop = $(this).scrollTop()+ $menuButtonHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
$menuLink
.parent().removeClass("active").end()
.filter("[href='#"+id+"']").parent().addClass("active");
}
// Active Menu Link href Attribute
activeMenuLinkHref = $('.menu-li.active > .menu-a').attr('href');
// console.log('activeMenuLinkHref '+activeMenuLinkHref);
}
scrollSpy()
$(window).scroll(function(e){
scrollSpy()
});
// On Stop of Scrolling get Active Menu Link Href and set window.location.hash
// --------------------------------------------------------------------------- //
// Scroll Stop Function
//---------------------//
// https://stackoverflow.com/questions/8931605/fire-event-after-scrollling-scrollbars-or-mousewheel-with-javascript
// http://stackoverflow.com/a/8931685/1010918
// http://jsfiddle.net/fbSbT/1/
// http://jsfiddle.net/fbSbT/87/
(function(){
var special = jQuery.event.special,
uid1 = 'D' + (+new Date()),
uid2 = 'D' + (+new Date() + 1);
special.scrollstart = {
setup: function() {
var timer,
handler = function(evt) {
var _self = this,
_args = arguments;
if (timer) {
clearTimeout(timer);
} else {
evt.type = 'scrollstart';
// throws "TypeError: jQuery.event.handle is undefined"
// jQuery.event.handle.apply(_self, _args);
// solution
// http://stackoverflow.com/a/20809936/1010918
// replace jQuery.event.handle.apply with jQuery.event.dispatch.apply
jQuery.event.dispatch.apply(_self, _args);
}
timer = setTimeout( function(){
timer = null;
}, special.scrollstop.latency);
};
jQuery(this).bind('scroll', handler).data(uid1, handler);
},
teardown: function(){
jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
}
};
special.scrollstop = {
latency: 250,
setup: function() {
var timer,
handler = function(evt) {
var _self = this,
_args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout( function(){
timer = null;
evt.type = 'scrollstop';
// throws "TypeError: jQuery.event.handle is undefined"
// jQuery.event.handle.apply(_self, _args);
// solution
// http://stackoverflow.com/a/20809936/1010918
// replace jQuery.event.handle.apply with jQuery.event.dispatch.apply
jQuery.event.dispatch.apply(_self, _args);
}, special.scrollstop.latency);
};
jQuery(this).bind('scroll', handler).data(uid2, handler);
},
teardown: function() {
jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
}
};
})();
// Scroll Stop Function Called
//----------------------------//
$(window).on("scrollstop", function() {
// window.history.pushState(null, null, activeMenuLinkHref);
// window.history.replaceState(null, null, activeMenuLinkHref);
// http://stackoverflow.com/a/1489802/1010918 //
// works best really
hash = activeMenuLinkHref.replace( /^#/, '' );
console.log('hash '+hash);
var node = $( '#' + hash );
if ( node.length ) {
node.attr( 'id', '' );
// console.log('node.attr id'+node.attr( 'id', '' ));
}
document.location.hash = hash;
if ( node.length ) {
node.attr( 'id', hash );
}
});
CSS
.console1{
position: fixed;
z-index: 9999;
top:0;
right:0;
background-color: #fff;
border: 2px solid red;
}
.console2{
position: fixed;
z-index: 9999;
bottom:0;
right:0;
background-color: #fff;
border: 2px solid red;
}
I will also supply a jsfiddle in due time. ;)

Related

collapsing section and scrolling back to top

I am working on a long one-pager. Yes, I know, we hate one-pagers. At least I promise not to implement any parallax-effect, I promise :)
I have multiple sections I can open/close. This part works fine.
The problem: those sections get pretty long, and when they are being closed/collapsed, the user find himself somewhere in the middle of the one-pager.
So, when collapsing a section, I want it to collapse AND to smooth scroll back to the top/the start of the collapsed section.
Here my script:
// Section-Collapse
//---------------------------------------------------------
$("section a.read-more").click(function() {
if($(this).parents("section").hasClass("expanded")) {
var scrollAnchor = $(this).attr("data-scroll"),
scrollPoint = $(".anchor[data-anchor='" + scrollAnchor + "']").offset().top - 0;
$("body,html").animate({
scrollTop: scrollPoint
}, 1500, function() {
// close/collapse section
$(this).parents("section").addClass("close");
$("section.expanded.close div.expandable-content").slideUp();
$(this).parents("section").removeClass("expanded").removeClass("close");
alert("this test-message is being displayed");
});
} else {
// open section
$(this).parents("section").addClass("expanded");
$("section.expanded div.expandable-content").slideDown();
}
});
The problem: this part is not being executed EXCEPT the alert message, that one works. Although it is trying to open the dialog window multiple times and Firefox offers me to block this behavior.
// einklappen
$(this).parents("section").addClass("close");
$("section.expanded.close div.expandable-content").slideUp();
$(this).parents("section").removeClass("expanded").removeClass("close");
alert("this test-message is being displayed");
It scrolls back to top, to the anchor, but the section will not collapse...
Any ideas why it won't collapse?
Regards,
Milan
---------------------------UPDATE
So, it was a problem with the scope of variable "this".
This code here seems to work fine:
// Section-Collapse
//---------------------------------------------------------
$("section a.read-more").click(function() {
if($(this).parents("section").hasClass("expanded")) {
var scrollAnchor = $(this).attr("data-scroll"),
scrollPoint = $(".anchor[data-anchor='" + scrollAnchor + "']").offset().top - 0;
var global_this = $(this);
$("body,html").animate({
scrollTop: scrollPoint
}, 1500, function() {
// einklappen
global_this.parents("section").addClass("close");
$("section.expanded.close div.expandable-content").slideUp();
global_this.parents("section").removeClass("expanded").removeClass("close");
alert("this test-message is being displayed");
});
// return false;
} else {
// ausklappen
$(this).parents("section").addClass("expanded");
$("section.expanded div.expandable-content").slideDown();
}
});
What is bothering me: why this script tries to open multiple alert dialogs?

Accordion Functionality

I've put together an accordion script that works quite nicely (haven't cross-browser tested) and allows for lots of content inside each drawer to be accessed and visible on screen. A lot of times accordions open and cause issues with positioning after opening. Anyway, the code I'm using has a toggle active function and a scroll function being called on click.
function toggleActive(link){ // Set anchor to active
if ( $(link).hasClass("active") ) {
$(link).removeClass("active");
} else {
$(link).addClass("active");
};
};
function scrollToElement(selector, time, verticalOffset) { // param 1 = id, param 2 = speed
time = typeof(time) != 'undefined' ? time : 1000;
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $(selector);
offset = element.offset();
offsetTop = offset.top + verticalOffset;
$('html, body').animate({scrollTop: offsetTop }, time);
}
$('#accordion a').click(function(e) {
var link = '#' + event.target.id
$(".tab-content").slideUp();
$(".tab").removeClass("active");
toggleActive(link);
$(link).next().slideToggle("fast");
setTimeout(function() {
scrollToElement($(link), 500);
}, 500);
e.preventDefault();
});
So when clicked, all of the tabs are closed and made inactive, then the targeted "drawer" is opened and made active. If for any reason you click an already "active" drawer, it runs through the script again. What I'd like to do is place an IF statement that determines if what you just clicked is already open, and then simply close that drawer. Thanks in advance. I don't know why this is causing me headaches.
JSFiddle
As I understand you need another function as below:
function isAlreadyActive(link)
{
if ( $(link).hasClass("active") ) {
$(link).removeClass("active");
return true;
} else {
return false;
};
}
And you should call that function in your click event. This function will check if the link already active, if so just deactivates it and changes as you want.
$('#accordion a').click(function(e) {
var link = '#' + event.target.id
/* if it is already active, just deactivate it and exit*/
if(isAlreadyActive(link)){
return false;
}
$(".tab-content").slideUp();
$(".tab").removeClass("active");
toggleActive(link);
$(link).next().slideToggle("fast");
setTimeout(function() {
scrollToElement($(link), 500);
}, 500);
e.preventDefault();
});
I hope this helps.

Trying to get my slideshow plugin to infinitely loop (by going back to the first state)

I wrote a slideshow plugin, but for some reason maybe because I've been working on it all day, I can't figure out exactly how to get it to go back to state one, once it's reached the very last state when it's on auto mode.
I'm thinking it's an architectual issue at this point, because basically I'm attaching the amount to scroll left to (negatively) for each panel (a panel contains 4 images which is what is currently shown to the user). The first tab should get: 0, the second 680, the third, 1360, etc. This is just done by calculating the width of the 4 images plus the padding.
I have it on a setTimeout(function(){}) currently to automatically move it which works pretty well (unless you also click tabs, but that's another issue). I just want to make it so when it's at the last state (numTabs - 1), to animate and move its state back to the first one.
Code:
(function($) {
var methods = {
init: function(options) {
var settings = $.extend({
'speed': '1000',
'interval': '1000',
'auto': 'on'
}, options);
return this.each(function() {
var $wrapper = $(this);
var $sliderContainer = $wrapper.find('.js-slider-container');
$sliderContainer.hide().fadeIn();
var $tabs = $wrapper.find('.js-slider-tabs li a');
var numTabs = $tabs.size();
var innerWidth = $wrapper.find('.js-slider-container').width();
var $elements = $wrapper.find('.js-slider-container a');
var $firstElement = $elements.first();
var containerHeight = $firstElement.height();
$sliderContainer.height(containerHeight);
// Loop through each list element in `.js-slider-tabs` and add the
// distance to move for each "panel". A panel in this example is 4 images
$tabs.each(function(i) {
// Set amount to scroll for each tab
if (i === 1) {
$(this).attr('data-to-move', innerWidth + 20); // 20 is the padding between elements
} else {
$(this).attr('data-to-move', innerWidth * (i) + (i * 20));
}
});
// If they hovered on the panel, add paused to the data attribute
$('.js-slider-container').hover(function() {
$sliderContainer.attr('data-paused', true);
}, function() {
$sliderContainer.attr('data-paused', false);
});
// Start the auto slide
if (settings.auto === 'on') {
methods.auto($tabs, settings, $sliderContainer);
}
$tabs.click(function() {
var $tab = $(this);
var $panelNum = $(this).attr('data-slider-panel');
var $amountToMove = $(this).attr('data-to-move');
// Remove the active class of the `li` if it contains it
$tabs.each(function() {
var $tab = $(this);
if ($tab.parent().hasClass('active')) {
$tab.parent().removeClass('active');
}
});
// Add active state to current tab
$tab.parent().addClass('active');
// Animate to panel position
methods.animate($amountToMove, settings);
return false;
});
});
},
auto: function($tabs, settings, $sliderContainer) {
$tabs.each(function(i) {
var $amountToMove = $(this).attr('data-to-move');
setTimeout(function() {
methods.animate($amountToMove, settings, i, $sliderContainer);
}, i * settings.interval);
});
},
animate: function($amountToMove, settings, i, $sliderContainer) {
// Animate
$('.js-slider-tabs li').eq(i - 1).removeClass('active');
$('.js-slider-tabs li').eq(i).addClass('active');
$('#js-to-move').animate({
'left': -$amountToMove
}, settings.speed, 'linear', function() {});
}
};
$.fn.slider = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
return false;
}
};
})(jQuery);
$(window).ready(function() {
$('.js-slider').slider({
'speed': '10000',
'interval': '10000',
'auto': 'on'
});
});​
The auto and animate methods are where the magic happens. The parameters speed is how fast it's animated and interval is how often, currently set at 10 seconds.
Can anyone help me figure out how to get this to "infinitely loop", if you will?
Here is a JSFiddle
It would probably be better to let go of the .each() and setTimeout() combo and use just setInterval() instead. Using .each() naturally limits your loop to the length of your collection, so it's better to use a looping mechanism that's not, and that you can break at any point you choose.
Besides, you can readily identify the current visible element by just checking for .active, from what I can see.
You'd probably need something like this:
setInterval(function () {
// do this check here.
// it saves you a function call and having to pass in $sliderContainer
if ($sliderContainer.attr('data-paused') === 'true') { return; }
// you really need to just pass in the settings object.
// the current element you can identify (as mentioned),
// and $amountToMove is derivable from that.
methods.animate(settings);
}, i * settings.interval);
// ...
// cache your slider tabs outside of the function
// and just form a closure on that to speed up your manips
var slidertabs = $('.js-slider-tabs');
animate : function (settings) {
// identify the current tab
var current = slidertabs.find('li.active'),
// and then do some magic to determine the next element in the loop
next = current.next().length >= 0 ?
current.next() :
slidertabs.find('li:eq(0)')
;
current.removeClass('active');
next.addClass('active');
// do your stuff
};
The code is not optimized, but I hope you see where I'm getting at here.

How to stop sliding if only one <li> using anythingSlider(jQuery plugin)?

I'm currently using the anythingSlider plugin, it works totally fine except when there is only one <li>.
The <li>s are generated from the database so sometimes there's only one.
However, the anythingSlider plugin still tries to slide through the <li>s, it works by sliding back to the first slide. Although this doesn't look great.
Does anybody know of a way of stopping it sliding if there's only one <li>?
-- EDIT --
Hi!
Can anybody else help with this? I've tried the solution by Greg and I've also tried:
if (banners<1) {
.anythingSlider({
startStopped: true,
buildNavigation: false
});
}
'banners' is my variable that I'm calling.
And this disables the anythingSlider function altogether.
Help please?!
-- EDIT 2 --
The original code is in the page of the html
<script type="text/javascript">
var banners=[];
banners[0]="http://image.ebuyer.com/customer/promos/UK/AcerAspire5536.jpg";
//banners[1]="http://image.ebuyer.com/customer/promos/2150/banner.jpg";
//banners[2]="http://image.ebuyer.com/customer/promos/UK/257653_FerrariOne_tb20091026.jpg";
//banners[3]="http://image.ebuyer.com/customer/promos/UK/247038_compaq_images/247038_compaq_incentive_banner20090814.jpg"; //added 03/09/2009
//banners[4]="http://image.ebuyer.com/customer/promos/UK/247858-samsung-tv-comp-tb20090817.jpg"; //added 19/08/2009
var bannerLink=[];
bannerLink[0]="http://www.ebuyer.com/product/173536";
//bannerLink[1]="/special/2150";
//bannerLink[2]="/product/172295";
//bannerLink[3]="/compaq-cash-incentive";
//bannerLink[4]="/special/2101";
var bannerAlt=[];
bannerAlt[0]="Acer Aspire 5536";
//bannerAlt[1]="The X5 range for Asus";
//bannerAlt[2]="Acer Ferrari One Laptop";
//bannerAlt[3]="Buy these three products together and claim £75 cashback";
//bannerAlt[4]="Win a Samsung 46in LCV TV";
</script>
It's then being actioned by this file: http://image.ebuyer.com/customer/promos/js/topbanners.js
// function to import css and javascript from external locations
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
// importing css and javascript
loadjscssfile("http://static.ebuyer.com/css/slider.css", "css") ////dynamically load and add this .css file
// setting the variables
var banner = document.getElementById('tehBanner');
var link = document.getElementById('tehLink');
// this function creates the tracking tags
function tracking (x) {
if (x.indexOf("?")>=0){x+='&tb='+(i+1);}else{x+='?tb='+(i+1);}
return x
}
// telling the javascript to display all available variables
for (var i in banners) {
banner.alt = bannerAlt[i];
link.href = tracking(bannerLink[i]);
banner.src = banners[i];
document.write('' + '<img src="' + banners[i] + '" id="slide-image" alt="' + bannerAlt[i] + '" />');
}
// remove the original banner
$ ('a#tehLink').parent().remove();
// hide banners to begin with
$('a.slide-link').hide();
/*
anythingSlider v1.1
By Chris Coyier: http://css-tricks.com
with major improvements by Doug Neiner: http://pixelgraphics.us/
based on work by Remy Sharp: http://jqueryfordesigners.com/
To use the navigationFormatter function, you must have a function that
accepts two paramaters, and returns a string of HTML text.
index = integer index (1 based);
panel = jQuery wrapped LI item this tab references
#return = Must return a string of HTML/Text
navigationFormatter: function(index, panel){
return index + " Panel"; // This would have each tab with the text 'X Panel' where X = index
}
*/
(function($){
$.anythingSlider = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Set up a few defaults
base.currentPage = 1;
base.timer = null;
base.playing = false;
// Add a reverse reference to the DOM object
base.$el.data("AnythingSlider", base);
base.init = function(){
base.options = $.extend({},$.anythingSlider.defaults, options);
// Cache existing DOM elements for later
base.$wrapper = base.$el.find('> div').css('overflow', 'hidden');
base.$slider = base.$wrapper.find('> ul');
base.$items = base.$slider.find('> li');
base.$single = base.$items.filter(':first');
// Build the navigation if needed
if(base.options.buildNavigation) base.buildNavigation();
// Get the details
base.singleWidth = base.$single.outerWidth();
base.pages = base.$items.length;
// Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
// This supports the "infinite" scrolling
base.$items.filter(':first').before(base.$items.filter(':last').clone().addClass('cloned'));
base.$items.filter(':last' ).after(base.$items.filter(':first').clone().addClass('cloned'));
// We just added two items, time to re-cache the list
base.$items = base.$slider.find('> li'); // reselect
// Setup our forward/backward navigation
base.buildNextBackButtons();
// If autoPlay functionality is included, then initialize the settings
if(base.options.autoPlay) {
base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
base.buildAutoPlay();
};
// If pauseOnHover then add hover effects
if(base.options.pauseOnHover) {
base.$el.hover(function(){
base.clearTimer();
}, function(){
base.startStop(base.playing);
});
}
// If a hash can not be used to trigger the plugin, then go to page 1
if((base.options.hashTags == true && !base.gotoHash()) || base.options.hashTags == false){
base.setCurrentPage(1);
};
};
base.gotoPage = function(page, autoplay){
// When autoplay isn't passed, we stop the timer
if(autoplay !== true) autoplay = false;
if(!autoplay) base.startStop(false);
if(typeof(page) == "undefined" || page == null) {
page = 1;
base.setCurrentPage(1);
};
// Just check for bounds
if(page > base.pages + 1) page = base.pages;
if(page < 0 ) page = 1;
var dir = page < base.currentPage ? -1 : 1,
n = Math.abs(base.currentPage - page),
left = base.singleWidth * dir * n;
base.$wrapper.filter(':not(:animated)').animate({
scrollLeft : '+=' + left
}, base.options.animationTime, base.options.easing, function () {
if (page == 0) {
base.$wrapper.scrollLeft(base.singleWidth * base.pages);
page = base.pages;
} else if (page > base.pages) {
base.$wrapper.scrollLeft(base.singleWidth);
// reset back to start position
page = 1;
};
base.setCurrentPage(page);
});
};
base.setCurrentPage = function(page, move){
// Set visual
if(base.options.buildNavigation){
base.$nav.find('.cur').removeClass('cur');
$(base.$navLinks[page - 1]).addClass('cur');
};
// Only change left if move does not equal false
if(move !== false) base.$wrapper.scrollLeft(base.singleWidth * page);
// Update local variable
base.currentPage = page;
};
base.goForward = function(autoplay){
if(autoplay !== true) autoplay = false;
base.gotoPage(base.currentPage + 1, autoplay);
};
base.goBack = function(){
base.gotoPage(base.currentPage - 1);
};
// This method tries to find a hash that matches panel-X
// If found, it tries to find a matching item
// If that is found as well, then that item starts visible
base.gotoHash = function(){
if(/^#?panel-\d+$/.test(window.location.hash)){
var index = parseInt(window.location.hash.substr(7));
var $item = base.$items.filter(':eq(' + index + ')');
if($item.length != 0){
base.setCurrentPage(index);
return true;
};
};
return false; // A item wasn't found;
};
// Creates the numbered navigation links
base.buildNavigation = function(){
base.$nav = $("<div id='thumbNav'></div>").appendTo(base.$el);
base.$items.each(function(i,el){
var index = i + 1;
var $a = $("<a href='#'></a>");
// If a formatter function is present, use it
if( typeof(base.options.navigationFormatter) == "function"){
$a.html(base.options.navigationFormatter(index, $(this)));
} else {
$a.text(index);
}
$a.click(function(e){
base.gotoPage(index);
if (base.options.hashTags)
base.setHash('panel-' + index);
e.preventDefault();
});
base.$nav.append($a);
});
base.$navLinks = base.$nav.find('> a');
};
// Creates the Forward/Backward buttons
base.buildNextBackButtons = function(){
var $forward = $('<a class="arrow forward">></a>'),
$back = $('<a class="arrow back"><</a>');
// Bind to the forward and back buttons
$back.click(function(e){
base.goBack();
e.preventDefault();
});
$forward.click(function(e){
base.goForward();
e.preventDefault();
});
// Append elements to page
base.$wrapper.after($back).after($forward);
};
// Creates the Start/Stop button
base.buildAutoPlay = function(){
base.$startStop = $("<a href='#' id='start-stop'></a>").html(base.playing ? base.options.stopText : base.options.startText);
base.$el.append(base.$startStop);
base.$startStop.click(function(e){
base.startStop(!base.playing);
e.preventDefault();
});
// Use the same setting, but trigger the start;
base.startStop(base.playing);
};
// Handles stopping and playing the slideshow
// Pass startStop(false) to stop and startStop(true) to play
base.startStop = function(playing){
if(playing !== true) playing = false; // Default if not supplied is false
// Update variable
base.playing = playing;
// Toggle playing and text
base.$startStop.toggleClass("playing", playing).html( playing ? base.options.stopText : base.options.startText );
if(playing){
base.clearTimer(); // Just in case this was triggered twice in a row
base.timer = window.setInterval(function(){
base.goForward(true);
}, base.options.delay);
} else {
base.clearTimer();
};
};
base.clearTimer = function(){
// Clear the timer only if it is set
if(base.timer) window.clearInterval(base.timer);
};
// Taken from AJAXY jquery.history Plugin
base.setHash = function ( hash ) {
// Write hash
if ( typeof window.location.hash !== 'undefined' ) {
if ( window.location.hash !== hash ) {
window.location.hash = hash;
};
} else if ( location.hash !== hash ) {
location.hash = hash;
};
// Done
return hash;
};
// <-- End AJAXY code
// Trigger the initialization
base.init();
};
$.anythingSlider.defaults = {
easing: "swing", // Anything other than "linear" or "swing" requires the easing plugin
autoPlay: true, // This turns off the entire FUNCTIONALY, not just if it starts running or not
startStopped: false, // If autoPlay is on, this can force it to start stopped
delay: 3000, // How long between slide transitions in AutoPlay mode
animationTime: 600, // How long the slide transition takes
hashTags: true, // Should links change the hashtag in the URL?
buildNavigation: true, // If true, builds and list of anchor links to link to each slide
pauseOnHover: true, // If true, and autoPlay is enabled, the show will pause on hover
startText: "Start", // Start text
stopText: "Stop", // Stop text
navigationFormatter: null // Details at the top of the file on this use (advanced use)
};
$.fn.anythingSlider = function(options){
if(typeof(options) == "object"){
return this.each(function(i){
(new $.anythingSlider(this, options));
// This plugin supports multiple instances, but only one can support hash-tag support
// This disables hash-tags on all items but the first one
options.hashTags = false;
});
} else if (typeof(options) == "number") {
return this.each(function(i){
var anySlide = $(this).data('AnythingSlider');
if(anySlide){
anySlide.gotoPage(options);
}
});
}
};
})(jQuery);
// this function wraps the elements in the neccessary tags to work with anything Slider
$ (document).ready(function() {
$('a.slide-link')
.wrap('<li class="slide-list-item"></li>');
$('li.slide-list-item')
.wrapAll('<ul id="slide-list"></ul>');
$('ul#slide-list')
.wrapAll('<div class="wrapper"></div>');
$('div.wrapper')
.wrapAll('<div class="anythingSlider internalSlider"></div>');
$('.anythingSlider')
.anythingSlider({
easing: "swing", // Anything other than "linear" or "swing" requires the easing plugin
autoPlay: true, // This turns off the entire FUNCTIONALY, not just if it starts running or not
startStopped: false, // If autoPlay is on, this can force it to start stopped
delay: 7000, // How long between slide transitions in AutoPlay mode
animationTime: 600, // How long the slide transition takes
hashTags: false, // Should links change the hashtag in the URL?
buildNavigation: true, // If true, builds and list of anchor links to link to each slide
pauseOnHover: true, // If true, and autoPlay is enabled, the show will pause on hover
startText: "Start", // Start text
stopText: "Stop", // Stop text
navigationFormatter: null // Details at the top of the file on this use (advanced use)
});
$('a.slide-link').show();
});
It's a bit of a hash job but works fine as long as there's more than one <li>
Try this:
// this function wraps the elements in the neccessary tags to work with anything Slider
$ (document).ready(function() {
$('a.slide-link')
.wrap('<li class="slide-list-item"></li>');
$('li.slide-list-item')
.wrapAll('<ul id="slide-list"></ul>');
$('ul#slide-list')
.wrapAll('<div class="wrapper"></div>');
$('div.wrapper')
.wrapAll('<div class="anythingSlider internalSlider"></div>');
if(banners.length > 1){
autoplayval= true;
} else {
autoplayval= false;
}
$('.anythingSlider')
.anythingSlider({
easing: "swing", // Anything other than "linear" or "swing" requires the easing plugin
autoPlay: autoplayval, // This turns off the entire FUNCTIONALY, not just if it starts running or not
startStopped: false, // If autoPlay is on, this can force it to start stopped
delay: 7000, // How long between slide transitions in AutoPlay mode
animationTime: 600, // How long the slide transition takes
hashTags: false, // Should links change the hashtag in the URL?
buildNavigation: true, // If true, builds and list of anchor links to link to each slide
pauseOnHover: true, // If true, and autoPlay is enabled, the show will pause on hover
startText: "Start", // Start text
stopText: "Stop", // Stop text
navigationFormatter: null // Details at the top of the file on this use (advanced use)
});
$('a.slide-link').show();
});
Changing this
$('.anythingSlider').anythingSlider({...});
to this
$('.anythingSlider:has(li:nth-child(2)').anythingSlider({...});
should do it
This assumes you don't have nested lists.
I had this problem and could only resolve this with a new version of the plugin: v1.5.3
URL: https://github.com/ProLoser/AnythingSlider/downloads
Once you've got the latest version, only change one line:
base.setCurrentPage(startPanel, false); // added to trigger events for FX code
When I have only one <li> the anythingControls element's style is display=none.
This will only activate the slider if more than 1 <LI> elements are present:
jQuery("#sliderDiv:has(>li:eq(1))").anythingSlider({...})
it assumes your HTML structure is like this:
<div id="sliderDiv">
<li>Offer 1</li>
<li>Offer 2</li>
</div>
You'll need something like
if($([ULELEMENT]).children('li').length > 1){
//Your code
}
Something along those lines. If you post your code, I can give it a try.

longtail player + anythingslider + event listeners

I've implemented the AnythingSlider (http://css-tricks.com/anythingslider-jquery-plugin/) using image and video content (videos use the longtail flv player - licensed version 5).
Problem: When the user plays the video, the slideshow doesn't know this has happened, so the slideshow keeps cycling while the video runs. So you have the slideshow running - and user can hear the audio but the video has cycled off.
UPDATE - here is a link to see what's going on: http://silverberry.org/beta/slider-longtail/
I'm trying to figure out an event-listener that will look and see when the LONGTAIL player is in PLAYING state and signals to the AnythingSlider that it needs to STOP.
Here's what I've got so far ... the video player event listeners are working (right now I have alerts popping up so that I can be sure the events are being heard). An alert pops up with the player is initialized .. and alert pops up when we press the PLAY button on the video ... and an alert pops up when the video STOPS playing. But ... I've yet to work out the proper syntax for signaling to the anythingslider to STOP!
I thought it would be this:
$VUslider.startStop(false);
Below is the code I have so far ... beginning with the code that initializes the slider.
function formatText(index, panel) {
return index + "";
}
$(function () {
$('.VUslider').VUslider({
autoPlay: true,
delay: 7000,
startStopped: false,
animationTime: 200,
hashTags: true,
buildNavigation: false,
pauseOnHover: true,
navigationFormatter: formatText
});
});
var player = null;
function playerReadyCallback(obj) {
player = document.getElementsByName(obj.id)[0];
alert('the videoplayer '+obj['id']+' has been instantiated');
player.addModelListener('STATE', 'stateMonitor');
}
function stateMonitor(obj) {
currentState = obj['newstate'];
if(currentState == 'PLAYING') {
alert ('the videoplayer '+obj['id']+' is playing now!');
$VUslider.startStop(false); // Trigger slideshow stop
}
if(obj.newstate == 'COMPLETED') {
alert ('the videoplayer '+obj['id']+' has stopped playing now!');
$VUslider.startStop(true); // Trigger slideshow start
}
}
FOR REFERENCE ... HERE IS THE ANYTHING SLIDER CODE:
(function($){
$.VUslider = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Set up a few defaults
base.currentPage = 1;
base.timer = null;
base.playing = false;
// Add a reverse reference to the DOM object
base.$el.data("AnythingSlider", base);
base.init = function(){
base.options = $.extend({},$.VUslider.defaults, options);
// Cache existing DOM elements for later
base.$wrapper = base.$el.find('> div').css('overflow', 'hidden');
base.$slider = base.$wrapper.find('> ul');
base.$items = base.$slider.find('> li');
base.$single = base.$items.filter(':first');
// Build the navigation if needed
if(base.options.buildNavigation) base.buildNavigation();
// Get the details
base.singleWidth = base.$single.outerWidth();
base.pages = base.$items.length;
// Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
// This supports the "infinite" scrolling
base.$items.filter(':first').before(base.$items.filter(':last').clone().addClass('cloned'));
base.$items.filter(':last' ).after(base.$items.filter(':first').clone().addClass('cloned'));
// We just added two items, time to re-cache the list
base.$items = base.$slider.find('> li'); // reselect
// Setup our forward/backward navigation
base.buildNextBackButtons();
// If autoPlay functionality is included, then initialize the settings
if(base.options.autoPlay) {
base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
base.buildAutoPlay();
};
// If pauseOnHover then add hover effects
if(base.options.pauseOnHover) {
base.$el.hover(function(){
base.clearTimer();
}, function(){
base.startStop(base.playing);
});
}
// If a hash can not be used to trigger the plugin, then go to page 1
if((base.options.hashTags == true && !base.gotoHash()) || base.options.hashTags == false){
base.setCurrentPage(1);
};
};
base.gotoPage = function(page, autoplay){
// When autoplay isn't passed, we stop the timer
if(autoplay !== true) autoplay = false;
if(!autoplay) base.startStop(false);
if(typeof(page) == "undefined" || page == null) {
page = 1;
base.setCurrentPage(1);
};
// Just check for bounds
if(page > base.pages + 1) page = base.pages;
if(page < 0 ) page = 1;
var dir = page < base.currentPage ? -1 : 1,
n = Math.abs(base.currentPage - page),
left = base.singleWidth * dir * n;
base.$wrapper.filter(':not(:animated)').animate({
scrollLeft : '+=' + left
}, base.options.animationTime, base.options.easing, function () {
if (page == 0) {
base.$wrapper.scrollLeft(base.singleWidth * base.pages);
page = base.pages;
} else if (page > base.pages) {
base.$wrapper.scrollLeft(base.singleWidth);
// reset back to start position
page = 1;
};
base.setCurrentPage(page);
});
};
base.setCurrentPage = function(page, move){
// Set visual
if(base.options.buildNavigation){
base.$nav.find('.cur').removeClass('cur');
$(base.$navLinks[page - 1]).addClass('cur');
};
// Only change left if move does not equal false
if(move !== false) base.$wrapper.scrollLeft(base.singleWidth * page);
// Update local variable
base.currentPage = page;
};
base.goForward = function(autoplay){
if(autoplay !== true) autoplay = false;
base.gotoPage(base.currentPage + 1, autoplay);
};
base.goBack = function(){
base.gotoPage(base.currentPage - 1);
};
// This method tries to find a hash that matches panel-X
// If found, it tries to find a matching item
// If that is found as well, then that item starts visible
base.gotoHash = function(){
if(/^#?panel-\d+$/.test(window.location.hash)){
var index = parseInt(window.location.hash.substr(7));
var $item = base.$items.filter(':eq(' + index + ')');
if($item.length != 0){
base.setCurrentPage(index);
return true;
};
};
return false; // A item wasn't found;
};
// Creates the numbered navigation links
base.buildNavigation = function(){
base.$nav = $("<div id='thumbNav'></div>").appendTo(base.$el);
base.$items.each(function(i,el){
var index = i + 1;
var $a = $("<a href='#'></a>");
// If a formatter function is present, use it
if( typeof(base.options.navigationFormatter) == "function"){
$a.html(base.options.navigationFormatter(index, $(this)));
} else {
$a.text(index);
}
$a.click(function(e){
base.gotoPage(index);
if (base.options.hashTags)
base.setHash('panel-' + index);
e.preventDefault();
});
base.$nav.append($a);
});
base.$navLinks = base.$nav.find('> a');
};
// Creates the Forward/Backward buttons
base.buildNextBackButtons = function(){
var $forward = $('<a class="arrow forward">></a>'),
$back = $('<a class="arrow back"><</a>');
// Bind to the forward and back buttons
$back.click(function(e){
base.goBack();
e.preventDefault();
});
$forward.click(function(e){
base.goForward();
e.preventDefault();
});
// Append elements to page
base.$wrapper.after($back).after($forward);
};
// Creates the Start/Stop button
base.buildAutoPlay = function(){
base.$startStop = $("<a href='#' id='start-stop'></a>").html(base.playing ? base.options.stopText : base.options.startText);
base.$el.append(base.$startStop);
base.$startStop.click(function(e){
base.startStop(!base.playing);
e.preventDefault();
});
// Use the same setting, but trigger the start;
base.startStop(base.playing);
};
// Handles stopping and playing the slideshow
// Pass startStop(false) to stop and startStop(true) to play
base.startStop = function(playing){
if(playing !== true) playing = false; // Default if not supplied is false
// Update variable
base.playing = playing;
// Toggle playing and text
if(base.options.autoPlay) base.$startStop.toggleClass("playing", playing).html( playing ? base.options.stopText : base.options.startText );
if(playing){
base.clearTimer(); // Just in case this was triggered twice in a row
base.timer = window.setInterval(function(){
base.goForward(true);
}, base.options.delay);
} else {
base.clearTimer();
};
};
base.clearTimer = function(){
// Clear the timer only if it is set
if(base.timer) window.clearInterval(base.timer);
};
// Taken from AJAXY jquery.history Plugin
base.setHash = function ( hash ) {
// Write hash
if ( typeof window.location.hash !== 'undefined' ) {
if ( window.location.hash !== hash ) {
window.location.hash = hash;
};
} else if ( location.hash !== hash ) {
location.hash = hash;
};
// Done
return hash;
};
// <-- End AJAXY code
// Trigger the initialization
base.init();
};
$.VUslider.defaults = {
easing: "swing", // Anything other than "linear" or "swing" requires the easing plugin
autoPlay: true, // This turns off the entire FUNCTIONALY, not just if it starts running or not
startStopped: false, // If autoPlay is on, this can force it to start stopped
delay: 3000, // How long between slide transitions in AutoPlay mode
animationTime: 600, // How long the slide transition takes
hashTags: true, // Should links change the hashtag in the URL?
buildNavigation: true, // If true, builds and list of anchor links to link to each slide
pauseOnHover: true, // If true, and autoPlay is enabled, the show will pause on hover
startText: "Start", // Start text
stopText: "Stop", // Stop text
navigationFormatter: null // Details at the top of the file on this use (advanced use)
};
$.fn.VUslider = function(options){
if(typeof(options) == "object"){
return this.each(function(i){
(new $.VUslider(this, options));
// This plugin supports multiple instances, but only one can support hash-tag support
// This disables hash-tags on all items but the first one
options.hashTags = false;
});
} else if (typeof(options) == "number") {
return this.each(function(i){
var anySlide = $(this).data('AnythingSlider');
if(anySlide){
anySlide.gotoPage(options);
}
});
}
};
})(jQuery);
Are you setting $VUslider to equal $('.VUslider').VUslider({ . . }); ?
In your example code you are not.
You should be doing something like this:
$VUslider = $('.VUslider').VUslider({
autoPlay: true,
delay: 7000,
startStopped: false,
animationTime: 200,
hashTags: true,
buildNavigation: false,
pauseOnHover: true,
navigationFormatter: formatText
});
This is somewhat of a stab in the dark, so I'll try to explain my reasoning a bit.
After you've created the VUslider bits as you're already doing, try doing this to start/stop the slider:
$('.VUslider').VUslider.startStop(false);
// this will toggle between starting and stopping but doesn't give control
// to call start or stop specifically.
$('#start-stop').click();
When you call $('.VUslider').VUslider({...}), it doesn't return anything, so there's no handle to VUslider at that point ($.each(..) doesn't return anything). This will hopefully get you a reference to the script and to the startStop function.
HTH

Categories