Target ID instead of <li> - javascript

I am working on JavaScript accordion and somehow i struck on targeting accordion ID instead of its <li>
Basically, I want below to generate two accordion if there are two markups like this
<div id="st-accordion" class="st-accordion">
<ul>
<li>
{tag_name_nolink}
<div class="st-content">
{tag_Partners Module tag}
</div>
</li>
</ul>
</div>
If there are two <div id="st-accordion" class="st-accordion">.......</div> then it should display two working accordions but it is making two working accordions when there are two <li> in the div.
Here is the JS and Fiddles
WORKING | NOT WORKING
(function( window, $, undefined ) {
var $event = $.event, resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind( "resize", $event.special.smartresize.handler );
},
teardown: function() {
$(this).unbind( "resize", $event.special.smartresize.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
// set correct event type
event.type = "smartresize";
if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply( context, args );
}, execAsap === "execAsap"? 0 : 100 );
}
};
$.fn.smartresize = function( fn ) {
return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
};
$.Accordion = function( options, element ) {
this.$el = $( element );
// list items
this.$items = this.$el.children('ul').children('li');
// total number of items
this.itemsCount = this.$items.length;
// initialize accordion
this._init( options );
};
$.Accordion.defaults = {
// index of opened item. -1 means all are closed by default.
open : -1,
// if set to true, only one item can be opened. Once one item is opened, any other that is opened will be closed first
oneOpenedItem : false,
// speed of the open / close item animation
speed : 600,
// easing of the open / close item animation
easing : 'easeInOutExpo',
// speed of the scroll to action animation
scrollSpeed : 900,
// easing of the scroll to action animation
scrollEasing : 'easeInOutExpo'
};
$.Accordion.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Accordion.defaults, options );
// validate options
this._validate();
// current is the index of the opened item
this.current = this.options.open;
// hide the contents so we can fade it in afterwards
this.$items.find('div.st-content').hide();
// save original height and top of each item
this._saveDimValues();
// if we want a default opened item...
if( this.current != -1 )
this._toggleItem( this.$items.eq( this.current ) );
// initialize the events
this._initEvents();
},
_saveDimValues : function() {
this.$items.each( function() {
var $item = $(this);
$item.data({
originalHeight : $item.find('a:first').height(),
offsetTop : $item.offset().top
});
});
},
// validate options
_validate : function() {
// open must be between -1 and total number of items, otherwise we set it to -1
if( this.options.open < -1 || this.options.open > this.itemsCount - 1 )
this.options.open = -1;
},
_initEvents : function() {
var instance = this;
// open / close item
this.$items.find('a:first').bind('click.accordion', function( event ) {
var $item = $(this).parent();
// close any opened item if oneOpenedItem is true
if( instance.options.oneOpenedItem && instance._isOpened() && instance.current!== $item.index() ) {
instance._toggleItem( instance.$items.eq( instance.current ) );
}
// open / close item
instance._toggleItem( $item );
return false;
});
$(window).bind('smartresize.accordion', function( event ) {
// reset orinal item values
instance._saveDimValues();
// reset the content's height of any item that is currently opened
instance.$el.find('li.st-open').each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ) + $this.find('div.st-content').outerHeight( true ) );
});
// scroll to current
if( instance._isOpened() )
instance._scroll();
});
},
// checks if there is any opened item
_isOpened : function() {
return ( this.$el.find('li.st-open').length > 0 );
},
// open / close item
_toggleItem : function( $item ) {
var $content = $item.find('div.st-content');
( $item.hasClass( 'st-open' ) )
? ( this.current = -1, $content.stop(true, true).fadeOut( this.options.speed ), $item.removeClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' )
}, this.options.speed, this.options.easing ) )
: ( this.current = $item.index(), $content.stop(true, true).fadeIn( this.options.speed ), $item.addClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' ) + $content.outerHeight( true )
}, this.options.speed, this.options.easing ), this._scroll( this ) )
},
// scrolls to current item or last opened item if current is -1
_scroll : function( instance ) {
var instance = instance || this, current;
( instance.current !== -1 ) ? current = instance.current : current = instance.$el.find('li.st-open:last').index();
$('html, body').stop().animate({
scrollTop : ( instance.options.oneOpenedItem ) ? instance.$items.eq( current ).data( 'offsetTop' ) : instance.$items.eq( current ).offset().top
}, instance.options.scrollSpeed, instance.options.scrollEasing );
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.accordion = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
logError( "cannot call methods on accordion prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for accordion instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
$.data( this, 'accordion', new $.Accordion( options, this ) );
}
});
}
return this;
};
})( window, jQuery );
somebody help please?

You have 2 elements with the same ID, and ID must be unique, so all you have to do is using class instead of ID :
$(function() {
$('.st-accordion').accordion({
oneOpenedItem : true
});
});
here is the jsFiddle

Related

Get/Set the index of the last opened li using jquery

I am using an accordion and trying to achieve the below:
Every time there is a post back, display/expand the last opened/active li that was shown before. At the moment, the page is refreshed and go back to its initial stage (all li closed). Is it possible to achieve this ?
I tried different things but without success e.g. I tried to save the last opened/active li index into a hidden aspx text box but it didn't work. Also, I tried to save the index in a cookie but again without success.
$('#st-accordion').accordion({
open: -1
});
Can I replace the -1 with a dynamic way of getting the index of the last opened li without losing it after post back ? In addition, how can I handle situations that more than one li were opened/expanded.
Any ideas would be much appreciated.
<link rel="stylesheet" type="text/css" href="../Content/style.css" />
<script type="text/javascript" src="../Scripts/jquery.accordion.js">
</script>
<script type="text/javascript" src="../Scripts/jquery.easing.1.3.js"></script>
<asp:UpdatePanel ID="UpdatePanelForm" runat="server">
<ContentTemplate>
<h2><asp:Label ID="TitleLbl" runat="server" Text=""></asp:Label></h2>
<div class="wrapper">
<div id="st-accordion" class="st-accordion">
<ul>
<li>
Section 1<span class="st-arrow" />
<div class="st-content">
Content 1
</div>
</li>
<li>
Section 2<span class="st-arrow" />
<div class="st-content">
Content 2
</div>
</li>
<li>
Section 3<span class="st-arrow" />
<div class="st-content">
<asp:LinkButton ID="LinkButtonEdit" OnClick="LinkButtonEdit_Click" CommandName="Select" runat="server">Edit</asp:LinkButton>
</div>
</li>
</ul>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function pageLoad(sender, args) {
$(document).ready(function () {
$('#st-accordion').accordion({
open: -1
});
});
}
</script>
(function (window, $, undefined) {
/*
* smartresize: debounced resize event for jQuery
*
*
* Copyright 2011 #louis_remi
* Licensed under the MIT license.
*/
var $event = $.event, resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind( "resize", $event.special.smartresize.handler );
},
teardown: function() {
$(this).unbind( "resize", $event.special.smartresize.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
// set correct event type
event.type = "smartresize";
if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply( context, args );
}, execAsap === "execAsap"? 0 : 100 );
}
};
$.fn.smartresize = function( fn ) {
return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
};
$.Accordion = function( options, element ) {
this.$el = $( element );
// list items
this.$items = this.$el.children('ul').children('li');
// total number of items
this.itemsCount = this.$items.length;
// initialize accordion
this._init( options );
};
$.Accordion.defaults = {
// index of opened item. -1 means all are closed by default.
open : -1,
// if set to true, only one item can be opened. Once one item is opened, any other that is opened will be closed first
oneOpenedItem : false,
// speed of the open / close item animation
speed : 600,
// easing of the open / close item animation
easing : 'easeInOutExpo',
// speed of the scroll to action animation
scrollSpeed : 900,
// easing of the scroll to action animation
scrollEasing: 'easeInOutExpo'
};
$.Accordion.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Accordion.defaults, options );
// validate options
this._validate();
// current is the index of the opened item
this.current = this.options.open;
// hide the contents so we can fade it in afterwards
this.$items.find('div.st-content').hide();
// save original height and top of each item
this._saveDimValues();
// if we want a default opened item...
if( this.current != -1 )
this._toggleItem( this.$items.eq( this.current ) );
// initialize the events
this._initEvents();
},
_saveDimValues : function() {
this.$items.each( function() {
var $item = $(this);
$item.data({
originalHeight : $item.find('a:first').height(),
offsetTop : $item.offset().top
});
});
},
// validate options
_validate : function() {
// open must be between -1 and total number of items, otherwise we set it to -1
if( this.options.open < -1 || this.options.open > this.itemsCount - 1 )
this.options.open = -1;
},
_initEvents : function() {
var instance = this;
// open / close item
this.$items.find('a:first').bind('click.accordion', function( event ) {
var $item = $(this).parent();
// close any opened item if oneOpenedItem is true
if( instance.options.oneOpenedItem && instance._isOpened() && instance.current!== $item.index() ) {
instance._toggleItem( instance.$items.eq( instance.current ) );
}
// open / close item
instance._toggleItem( $item );
return false;
});
$(window).bind('smartresize.accordion', function( event ) {
// reset orinal item values
instance._saveDimValues();
// reset the content's height of any item that is currently opened
instance.$el.find('li.st-open').each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ) + $this.find('div.st-content').outerHeight( true ) );
});
// scroll to current
//if( instance._isOpened() )
//instance._scroll();
});
},
// checks if there is any opened item
_isOpened : function() {
return ( this.$el.find('li.st-open').length > 0 );
},
// open / close item
_toggleItem : function( $item ) {
var $content = $item.find('div.st-content');
( $item.hasClass( 'st-open' ) )
? ( this.current = -1, $content.stop(true, true).fadeOut( this.options.speed ), $item.removeClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' )
}, this.options.speed, this.options.easing ) )
: ( this.current = $item.index(), $content.stop(true, true).fadeIn( this.options.speed ), $item.addClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' ) + $content.outerHeight( true )
}, this.options.speed, this.options.easing ), this._scroll( this ) )
},
// scrolls to current item or last opened item if current is -1
_scroll : function( instance ) {
var instance = instance || this, current;
( instance.current !== -1 ) ? current = instance.current : current = instance.$el.find('li.st-open:last').index();
$('html, body').stop().animate({
scrolltop : ( instance.options.oneopeneditem ) ? instance.$items.eq( current ).data( 'offsettop' ) : instance.$items.eq( current ).offset().top
}, instance.options.scrollspeed, instance.options.scrolleasing );
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.accordion= function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
logError( "cannot call methods on accordion prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for accordion instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
$.data( this, 'accordion', new $.Accordion( options, this ) );
}
});
}
return this;
};
})(window, jQuery);
You can use sessionStorage in order to save some js variables with the last opened/expanded li, you can set it on open/expand event:
sessionStorage.SessionName = "SessionName";
sessionStorage.getItem("SessionName");
sessionStorage.setItem("SessionName","10");
Or you can use cookies (client side):
document.cookie

bootstrap accordian or hide and Show is not working under dynamic creation elements in jQuery

In one of my sample application, when click the particular items, it will show the pop up with description of the particular items. When I tried to put the bootstrap accordion or hide and show nothing works here, except jQuery delegate event handlers.
In grid.js is a third party plugins provide the dynamic element creation.
This is an li and a class called portfolio_description. Inside the class nothing gets triggered click event, hide or show, toggle etc, except delegate handler.
<ul>
<li>
<a data-description="data-description" data-largesrc="~/Content/example/gallery/intro_img4.jpg" data-title="Project Name 1" href="#"><img alt="" src="~/Content/example/gallery/intro_img4.jpg"></a>
<div class="portfolio_description">
<div class="block">
<div class="container">
<h2>Simple Collapsible</h2>
<p>Click on the button to toggle between showing and hiding content.</p>
<button class="btn btn-info" data-target="#demo" data-toggle="collapse" type="button">Simple collapsible</button>
<div class="collapse" id="demo">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
</div>
</li>
</ul>
Here is an plunker demo.
https://plnkr.co/edit/XY7A3D3YO7hoF8AulZpR?p=preview
output:
problem with collection :
Before and after removal of class portfolio description:
because of conflicting ID for accordion elements , Please update your code with unique id.
Same id exist in "portfolio_description" AND "gallery-expander" DIV.
Updated :
Please update your grid.js with below,
/*
* debouncedresize: special jQuery event that happens once after a window resize
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery-smartresize/blob/master/jquery.debouncedresize.js
*
* Copyright 2011 #louis_remi
* Licensed under the MIT license.
*/
var $event = $.event,
$special,
resizeTimeout,
previousItem,
accordionHTML;
$special = $event.special.debouncedresize = {
setup: function() {
$( this ).on( "resize", $special.handler );
},
teardown: function() {
$( this ).off( "resize", $special.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments,
dispatch = function() {
// set correct event type
event.type = "debouncedresize";
$event.dispatch.apply( context, args );
};
if ( resizeTimeout ) {
clearTimeout( resizeTimeout );
}
execAsap ?
dispatch() :
resizeTimeout = setTimeout( dispatch, $special.threshold );
},
threshold: 250
};
// ======================= imagesLoaded Plugin ===============================
// https://github.com/desandro/imagesloaded
// $('#my-container').imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images
// callback function gets image collection as argument
// this is the container
// original: MIT license. Paul Irish. 2010.
// contributors: Oren Solomianik, David DeSandro, Yiannis Chatzikonstantinou
// blank image data-uri bypasses webkit log warning (thx doug jones)
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
$.fn.imagesLoaded = function( callback ) {
var $this = this,
deferred = $.isFunction($.Deferred) ? $.Deferred() : 0,
hasNotify = $.isFunction(deferred.notify),
$images = $this.find('img').add( $this.filter('img') ),
loaded = [],
proper = [],
broken = [];
// Register deferred callbacks
if ($.isPlainObject(callback)) {
$.each(callback, function (key, value) {
if (key === 'callback') {
callback = value;
} else if (deferred) {
deferred[key](value);
}
});
}
function doneLoading() {
var $proper = $(proper),
$broken = $(broken);
if ( deferred ) {
if ( broken.length ) {
deferred.reject( $images, $proper, $broken );
} else {
deferred.resolve( $images );
}
}
if ( $.isFunction( callback ) ) {
callback.call( $this, $images, $proper, $broken );
}
}
function imgLoaded( img, isBroken ) {
// don't proceed if BLANK image, or image is already loaded
if ( img.src === BLANK || $.inArray( img, loaded ) !== -1 ) {
return;
}
// store element in loaded images array
loaded.push( img );
// keep track of broken and properly loaded images
if ( isBroken ) {
broken.push( img );
} else {
proper.push( img );
}
// cache image and its state for future calls
$.data( img, 'imagesLoaded', { isBroken: isBroken, src: img.src } );
// trigger deferred progress method if present
if ( hasNotify ) {
deferred.notifyWith( $(img), [ isBroken, $images, $(proper), $(broken) ] );
}
// call doneLoading and clean listeners if all images are loaded
if ( $images.length === loaded.length ){
setTimeout( doneLoading );
$images.unbind( '.imagesLoaded' );
}
}
// if no images, trigger immediately
if ( !$images.length ) {
doneLoading();
} else {
$images.bind( 'load.imagesLoaded error.imagesLoaded', function( event ){
// trigger imgLoaded
imgLoaded( event.target, event.type === 'error' );
}).each( function( i, el ) {
var src = el.src;
// find out if this image has been already checked for status
// if it was, and src has not changed, call imgLoaded on it
var cached = $.data( el, 'imagesLoaded' );
if ( cached && cached.src === src ) {
imgLoaded( el, cached.isBroken );
return;
}
// if complete is true and browser supports natural sizes, try
// to check for image status manually
if ( el.complete && el.naturalWidth !== undefined ) {
imgLoaded( el, el.naturalWidth === 0 || el.naturalHeight === 0 );
return;
}
// cached images don't fire load sometimes, so we reset src, but only when
// dealing with IE, or image is complete (loaded) and failed manual check
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
if ( el.readyState || el.complete ) {
el.src = BLANK;
el.src = src;
}
});
}
return deferred ? deferred.promise( $this ) : $this;
};
var Grid = (function() {
// list of items
var $grid = $( '#gallery-grid' ),
// the items
$items = $grid.children( 'li' ),
// current expanded item's index
current = -1,
// position (top) of the expanded item
// used to know if the preview will expand in a different row
previewPos = -1,
// extra amount of pixels to scroll the window
scrollExtra = 0,
// extra margin when expanded (between preview overlay and the next items)
marginExpanded = 10,
$window = $( window ), winsize,
$body = $( 'html, body' ),
// transitionend events
transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
// support for csstransitions
support = Modernizr.csstransitions,
// default settings
settings = {
minHeight : 500,
speed : 350,
easing : 'ease'
};
function init( config ) {
// the settings..
settings = $.extend( true, {}, settings, config );
// preload all images
$grid.imagesLoaded( function() {
// save item´s size and offset
saveItemInfo( true );
// get window´s size
getWinSize();
// initialize some events
initEvents();
} );
}
// add more items to the grid.
// the new items need to appended to the grid.
// after that call Grid.addItems(theItems);
function addItems( $newitems ) {
$items = $items.add( $newitems );
$newitems.each( function() {
var $item = $( this );
$item.data( {
offsetTop : $item.offset().top,
height : $item.height()
} );
} );
initItemsEvents( $newitems );
}
// saves the item´s offset top and height (if saveheight is true)
function saveItemInfo( saveheight ) {
$items.each( function() {
var $item = $( this );
$item.data( 'offsetTop', $item.offset().top );
if( saveheight ) {
$item.data( 'height', $item.height() );
}
} );
}
function initEvents() {
// when clicking an item, show the preview with the item´s info and large image.
// close the item if already expanded.
// also close if clicking on the item´s cross
initItemsEvents( $items );
// on window resize get the window´s size again
// reset some values..
$window.on( 'debouncedresize', function() {
scrollExtra = 0;
previewPos = -1;
// save item´s offset
saveItemInfo();
getWinSize();
var preview = $.data( this, 'preview' );
if( typeof preview != 'undefined' ) {
hidePreview();
}
} );
}
function initItemsEvents( $items ) {
$items.on( 'click', 'span.gallery-close', function() {
hidePreview();
return false;
} ).children( 'a' ).on( 'click', function(e) {
var $item = $( this ).parent();
// check if item already opened
current === $item.index() ? hidePreview() : showPreview( $item );
return false;
} );
}
function getWinSize() {
winsize = { width : $window.width(), height : $window.height() };
}
function showPreview( $item ) {
var preview = $.data( this, 'preview' ),
// item´s offset top
position = $item.data( 'offsetTop' );
scrollExtra = 0;
// if a preview exists and previewPos is different (different row) from item´s top then close it
if( typeof preview != 'undefined' ) {
// not in the same row
if( previewPos !== position ) {
// if position > previewPos then we need to take te current preview´s height in consideration when scrolling the window
if( position > previewPos ) {
scrollExtra = preview.height;
}
hidePreview();
}
// same row
else {
preview.update( $item );
return false;
}
}
// update previewPos
previewPos = position;
// initialize new preview for the clicked item
preview = $.data( this, 'preview', new Preview( $item ) );
// expand preview overlay
preview.open();
}
function hidePreview() {
current = -1;
var preview = $.data( this, 'preview' );
preview.close();
$.removeData( this, 'preview' );
}
// the preview obj / overlay
function Preview( $item ) {
this.$item = $item;
this.expandedIdx = this.$item.index();
this.create();
this.update();
}
Preview.prototype = {
create : function() {
if(typeof previousItem != 'undefined' || previousItem){
previousItem.append('<div class="portfolio_description">'+accordionHTML+'</div>')
}
// create Preview structure:
//this.$title = $( '<h3></h3>' );
this.$description = $( '<div></div>' );
//this.$href = $( 'Visit website' );
//this.$details = $( '<div class="gallery-details"></div>' ).append( this.$title, this.$description, this.$href );
this.$details = $( '<div class="gallery-details"></div>' ).append( this.$description );
//console.log(this);
this.$loading = $( '<div class="gallery-loading"></div>' );
this.$fullimage = $( '<div class="gallery-fullimg"></div>' ).append( this.$loading );
this.$closePreview = $( '<span class="gallery-close"></span>' );
this.$previewInner = $( '<div class="gallery-expander-inner"></div>' ).append( this.$closePreview, this.$fullimage, this.$details );
this.$previewEl = $( '<div class="gallery-expander"></div>' ).append( this.$previewInner );
// append preview element to the item
this.$item.append( this.getEl() );
// set the transitions for the preview and the item
if( support ) {
this.setTransition();
}
},
update : function( $item ) {
if(typeof previousItem != 'undefined' || previousItem){
previousItem.append('<div class="portfolio_description">'+accordionHTML+'</div>')
}
if( $item ) {
this.$item = $item;
}
// if already expanded remove class "gallery-expanded" from current item and add it to new item
if( current !== -1 ) {
var $currentItem = $items.eq( current );
$currentItem.removeClass( 'gallery-expanded' );
this.$item.addClass( 'gallery-expanded' );
// position the preview correctly
this.positionPreview();
}
// update current value
current = this.$item.index();
// update preview's content
var $itemEl = this.$item.children( 'a' ),
eldata = {
// href : $itemEl.attr( 'href' ),
// largesrc : $itemEl.data( 'largesrc' ),
largesrc : $itemEl.find('img').attr('src'),
// title : $itemEl.data( 'title' ),
// description : $itemEl.data( 'description' ),
description : $itemEl.parent().find('.portfolio_description').html()
//description : 'test'
};
//this.$title.html( eldata.title );
this.$description.html( eldata.description );
accordionHTML =eldata.description;
previousItem = this.$item;
this.$item.children( 'a' ).parent().find('.portfolio_description').remove();
//this.$href.attr( 'href', eldata.href );
var self = this;
// remove the current image in the preview
if( typeof self.$largeImg != 'undefined' ) {
self.$largeImg.remove();
}
// preload large image and add it to the preview
// for smaller screens we don´t display the large image (the media query will hide the fullimage wrapper)
if( self.$fullimage.is( ':visible' ) ) {
this.$loading.show();
$( '<img/>' ).load( function() {
var $img = $( this );
if( $img.attr( 'src' ) === self.$item.children('a').data( 'largesrc' ) ) {
self.$loading.hide();
self.$fullimage.find( 'img' ).remove();
self.$largeImg = $img.fadeIn( 350 );
self.$fullimage.append( self.$largeImg );
}
} ).attr( 'src', eldata.largesrc );
}
},
open : function() {
setTimeout( $.proxy( function() {
// set the height for the preview and the item
this.setHeights();
// scroll to position the preview in the right place
this.positionPreview();
}, this ), 25 );
},
close : function() {
var self = this,
onEndFn = function() {
if( support ) {
$( this ).off( transEndEventName );
}
self.$item.removeClass( 'gallery-expanded' );
self.$previewEl.remove();
self.$item.append('<div id="ss" class="portfolio_description">'+accordionHTML+'</div>')
};
setTimeout( $.proxy( function() {
if( typeof this.$largeImg !== 'undefined' ) {
this.$largeImg.fadeOut( 'fast' );
}
this.$previewEl.css( 'height', 0 );
// the current expanded item (might be different from this.$item)
var $expandedItem = $items.eq( this.expandedIdx );
$expandedItem.css( 'height', $expandedItem.data( 'height' ) ).on( transEndEventName, onEndFn );
if( !support ) {
onEndFn.call();
}
}, this ), 25 );
return false;
},
calcHeight : function() {
var heightPreview = winsize.height - this.$item.data( 'height' ) - marginExpanded,
itemHeight = winsize.height;
if( heightPreview < settings.minHeight ) {
heightPreview = settings.minHeight;
itemHeight = settings.minHeight + this.$item.data( 'height' ) + marginExpanded;
}
this.height = heightPreview;
this.itemHeight = itemHeight;
},
setHeights : function() {
var self = this,
onEndFn = function() {
if( support ) {
self.$item.off( transEndEventName );
}
self.$item.addClass( 'gallery-expanded' );
};
this.calcHeight();
this.$previewEl.css( 'height', this.height );
this.$item.css( 'height', this.itemHeight ).on( transEndEventName, onEndFn );
if( !support ) {
onEndFn.call();
}
},
positionPreview : function() {
// scroll page
// case 1 : preview height + item height fits in window´s height
// case 2 : preview height + item height does not fit in window´s height and preview height is smaller than window´s height
// case 3 : preview height + item height does not fit in window´s height and preview height is bigger than window´s height
var position = this.$item.data( 'offsetTop' ),
previewOffsetT = this.$previewEl.offset().top - scrollExtra,
scrollVal = this.height + this.$item.data( 'height' ) + marginExpanded <= winsize.height ? position : this.height < winsize.height ? previewOffsetT - ( winsize.height - this.height ) : previewOffsetT;
$body.animate( { scrollTop : scrollVal }, settings.speed );
},
setTransition : function() {
this.$previewEl.css( 'transition', 'height ' + settings.speed + 'ms ' + settings.easing );
this.$item.css( 'transition', 'height ' + settings.speed + 'ms ' + settings.easing );
},
getEl : function() {
return this.$previewEl;
}
}
return {
init : init,
addItems : addItems
};
})();

Responsive Multi-Level Menu - How to close menu when link is clicked?

I have a very simple menu, no sub menus and was curious how I would get the menu to close when I click on one of the links?
Plugin Home Page ->
Here is the code directly out of the .js file that comes in the zip when you download this menu. I really need to know what code to add and where to add it so that when I click a link it closes the menu.
;( function( $, window, undefined ) {
'use strict';
// global
var Modernizr = window.Modernizr, $body = $( 'body' );
$.DLMenu = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.DLMenu.defaults = {
// classes for the animation effects
animationClasses : { classin : 'dl-animate-in-1', classout : 'dl-animate-out-1' },
// callback: click a link that has a sub menu
// el is the link element (li); name is the level name
onLevelClick : function( el, name ) { return false; },
// callback: click a link that does not have a sub menu
// el is the link element (li); ev is the event obj
onLinkClick : function( el, ev ) { return false; }
};
$.DLMenu.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.DLMenu.defaults, options );
// cache some elements and initialize some variables
this._config();
var animEndEventNames = {
'WebkitAnimation' : 'webkitAnimationEnd',
'OAnimation' : 'oAnimationEnd',
'msAnimation' : 'MSAnimationEnd',
'animation' : 'animationend'
},
transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
};
// animation end event name
this.animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ] + '.dlmenu';
// transition end event name
this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.dlmenu',
// support for css animations and css transitions
this.supportAnimations = Modernizr.cssanimations,
this.supportTransitions = Modernizr.csstransitions;
this._initEvents();
},
_config : function() {
this.open = false;
this.$trigger = this.$el.children( '.dl-trigger' );
this.$menu = this.$el.children( 'ul.dl-menu' );
this.$menuitems = this.$menu.find( 'li:not(.dl-back)' );
this.$el.find( 'ul.dl-submenu' ).prepend( '<li class="dl-back">BACK</li>' );
this.$back = this.$menu.find( 'li.dl-back' );
},
_initEvents : function() {
var self = this;
this.$trigger.on( 'click.dlmenu', function() {
if( self.open ) {
self._closeMenu();
}
else {
self._openMenu();
}
return false;
} );
this.$menuitems.on( 'click.dlmenu', function( event ) {
event.stopPropagation();
var $item = $(this),
$submenu = $item.children( 'ul.dl-submenu' );
if( $submenu.length > 0 ) {
var $flyin = $submenu.clone().css( 'opacity', 0 ).insertAfter( self.$menu ),
onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classout ).addClass( 'dl-subview' );
$item.addClass( 'dl-subviewopen' ).parents( '.dl-subviewopen:first' ).removeClass( 'dl-subviewopen' ).addClass( 'dl-subview' );
$flyin.remove();
};
setTimeout( function() {
$flyin.addClass( self.options.animationClasses.classin );
self.$menu.addClass( self.options.animationClasses.classout );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
self.options.onLevelClick( $item, $item.children( 'a:first' ).text() );
} );
return false;
}
var link = $item.find('a').attr('href');
var hash = link.substring(link.indexOf('#')+1);
if( hash != "" ){
var elem = jQuery('div[data-anchor="'+hash+'"]');
autoScroll(elem);
self._closeMenu();
}else{
self.options.onLinkClick( $item, event );
}
} );
this.$back.on( 'click.dlmenu', function( event ) {
var $this = $( this ),
$submenu = $this.parents( 'ul.dl-submenu:first' ),
$item = $submenu.parent(),
$flyin = $submenu.clone().insertAfter( self.$menu );
var onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classin );
$flyin.remove();
};
setTimeout( function() {
$flyin.addClass( self.options.animationClasses.classout );
self.$menu.addClass( self.options.animationClasses.classin );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
$item.removeClass( 'dl-subviewopen' );
var $subview = $this.parents( '.dl-subview:first' );
if( $subview.is( 'li' ) ) {
$subview.addClass( 'dl-subviewopen' );
}
$subview.removeClass( 'dl-subview' );
} );
return false;
} );
},
closeMenu : function() {
if( this.open ) {
this._closeMenu();
}
},
_closeMenu : function() {
var self = this,
onTransitionEndFn = function() {
self.$menu.off( self.transEndEventName );
self._resetMenu();
};
this.$menu.removeClass( 'dl-menuopen' );
this.$menu.addClass( 'dl-menu-toggle' );
this.$trigger.removeClass( 'dl-active' );
if( this.supportTransitions ) {
this.$menu.on( this.transEndEventName, onTransitionEndFn );
}
else {
onTransitionEndFn.call();
}
this.open = false;
},
openMenu : function() {
if( !this.open ) {
this._openMenu();
}
},
_openMenu : function() {
var self = this;
// clicking somewhere else makes the menu close
$body.off( 'click' ).on( 'click.dlmenu', function() {
self._closeMenu() ;
} );
this.$menu.addClass( 'dl-menuopen dl-menu-toggle' ).on( this.transEndEventName, function() {
$( this ).removeClass( 'dl-menu-toggle' );
} );
this.$trigger.addClass( 'dl-active' );
this.open = true;
},
// resets the menu to its original state (first level of options)
_resetMenu : function() {
this.$menu.removeClass( 'dl-subview' );
this.$menuitems.removeClass( 'dl-subview dl-subviewopen' );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.dlmenu = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( !instance ) {
logError( "cannot call methods on dlmenu prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for dlmenu instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'dlmenu', new $.DLMenu( options, this ) );
}
});
}
return this;
};
} )( jQuery, window );
After looking at their demo, it seems you can call method plugins. Replace dl-menu with the id of your menu.
$('#dl-menu a').click(function(e) {
$('#dl-menu').dlmenu('closeMenu');
});

Trigger method defined in javascript object, but outside of the object itself

I suspect my question may be a bit obtuse, and I apologize. Here is what I am trying to achieve:
I am using this multi-level push menu, and it works fine out of the box. However, I would like the multi-level menu to close after a modal is submitted and closed. I am having a difficult time figuring out how to trigger this menu to close.
So, on to some code. Up first, the Javascript that runs the menu itself.
mlPushMenu.prototype = {
defaults : {
// overlap: there will be a gap between open levels
// cover: the open levels will be on top of any previous open level
type : 'overlap', // overlap || cover
// space between each overlaped level
levelSpacing : 40,
// classname for the element (if any) that when clicked closes the current level
backClass : 'mp-back'
},
_init : function() {
// if menu is open or not
this.open = false;
// level depth
this.level = 0;
// the moving wrapper
this.wrapper = document.getElementById( 'mp-pusher' );
// the mp-level elements
this.levels = Array.prototype.slice.call( this.el.querySelectorAll( 'div.mp-level' ) );
// save the depth of each of these mp-level elements
var self = this;
this.levels.forEach( function( el, i ) { el.setAttribute( 'data-level', getLevelDepth( el, self.el.id, 'mp-level' ) ); } );
// the menu items
this.menuItems = Array.prototype.slice.call( this.el.querySelectorAll( 'li' ) );
// if type == "cover" these will serve as hooks to move back to the previous level
this.levelBack = Array.prototype.slice.call( this.el.querySelectorAll( '.' + this.options.backClass ) );
// event type (if mobile use touch events)
this.eventtype = mobilecheck() ? 'touchstart' : 'click';
// add the class mp-overlap or mp-cover to the main element depending on options.type
classie.add( this.el, 'mp-' + this.options.type );
// initialize / bind the necessary events
this._initEvents();
},
_initEvents : function() {
var self = this;
// the menu should close if clicking somewhere on the body
var bodyClickFn = function( el ) {
self._resetMenu();
el.removeEventListener( self.eventtype, bodyClickFn );
};
// open (or close) the menu
this.trigger.addEventListener( this.eventtype, function( ev ) {
ev.stopPropagation();
ev.preventDefault();
if( self.open ) {
self._resetMenu();
}
else {
self._openMenu();
// the menu should close if clicking somewhere on the body (excluding clicks on the menu)
document.addEventListener( self.eventtype, function( ev ) {
if( self.open && !hasParent( ev.target, self.el.id ) ) {
bodyClickFn( this );
}
} );
}
} );
// opening a sub level menu
this.menuItems.forEach( function( el, i ) {
// check if it has a sub level
var subLevel = el.querySelector( 'div.mp-level' );
if( subLevel ) {
el.querySelector( 'a' ).addEventListener( self.eventtype, function( ev ) {
ev.preventDefault();
var level = closest( el, 'mp-level' ).getAttribute( 'data-level' );
if( self.level <= level ) {
ev.stopPropagation();
classie.add( closest( el, 'mp-level' ), 'mp-level-overlay' );
self._openMenu( subLevel );
}
} );
}
} );
// closing the sub levels :
// by clicking on the visible part of the level element
this.levels.forEach( function( el, i ) {
el.addEventListener( self.eventtype, function( ev ) {
ev.stopPropagation();
var level = el.getAttribute( 'data-level' );
if( self.level > level ) {
self.level = level;
self._closeMenu();
}
} );
} );
// by clicking on a specific element
this.levelBack.forEach( function( el, i ) {
el.addEventListener( self.eventtype, function( ev ) {
ev.preventDefault();
var level = closest( el, 'mp-level' ).getAttribute( 'data-level' );
if( self.level <= level ) {
ev.stopPropagation();
self.level = closest( el, 'mp-level' ).getAttribute( 'data-level' ) - 1;
self.level === 0 ? self._resetMenu() : self._closeMenu();
}
} );
} );
},
_openMenu : function( subLevel ) {
// increment level depth
++this.level;
// move the main wrapper
var levelFactor = ( this.level - 1 ) * this.options.levelSpacing,
translateVal = this.options.type === 'overlap' ? this.el.offsetWidth + levelFactor : this.el.offsetWidth;
this._setTransform( 'translate3d(' + translateVal + 'px,0,0)' );
if( subLevel ) {
// reset transform for sublevel
this._setTransform( '', subLevel );
// need to reset the translate value for the level menus that have the same level depth and are not open
for( var i = 0, len = this.levels.length; i < len; ++i ) {
var levelEl = this.levels[i];
if( levelEl != subLevel && !classie.has( levelEl, 'mp-level-open' ) ) {
this._setTransform( 'translate3d(-100%,0,0) translate3d(' + -1*levelFactor + 'px,0,0)', levelEl );
}
}
}
// add class mp-pushed to main wrapper if opening the first time
if( this.level === 1 ) {
classie.add( this.wrapper, 'mp-pushed' );
this.open = true;
}
// add class mp-level-open to the opening level element
classie.add( subLevel || this.levels[0], 'mp-level-open' );
},
// close the menu
_resetMenu : function() {
this._setTransform('translate3d(0,0,0)');
this.level = 0;
// remove class mp-pushed from main wrapper
classie.remove( this.wrapper, 'mp-pushed' );
this._toggleLevels();
this.open = false;
},
// close sub menus
_closeMenu : function() {
var translateVal = this.options.type === 'overlap' ? this.el.offsetWidth + ( this.level - 1 ) * this.options.levelSpacing : this.el.offsetWidth;
this._setTransform( 'translate3d(' + translateVal + 'px,0,0)' );
this._toggleLevels();
},
// translate the el
_setTransform : function( val, el ) {
el = el || this.wrapper;
el.style.WebkitTransform = val;
el.style.MozTransform = val;
el.style.transform = val;
},
// removes classes mp-level-open from closing levels
_toggleLevels : function() {
for( var i = 0, len = this.levels.length; i < len; ++i ) {
var levelEl = this.levels[i];
if( levelEl.getAttribute( 'data-level' ) >= this.level + 1 ) {
classie.remove( levelEl, 'mp-level-open' );
classie.remove( levelEl, 'mp-level-overlay' );
}
else if( Number( levelEl.getAttribute( 'data-level' ) ) == this.level ) {
classie.remove( levelEl, 'mp-level-overlay' );
}
}
}
}
The method I would like to invoke would be _resetMenu. I have tried this a couple of ways. The primary was trying to trigger the click event of the button that opens the menu:
<i class="fa fa-reorder"></i>
However:
$('#trigger').trigger('click');
does not work as expected. I would expect this to be fired:
// open (or close) the menu
this.trigger.addEventListener( this.eventtype, function( ev ) {
ev.stopPropagation();
ev.preventDefault();
if( self.open ) {
self._resetMenu();
}
else {
self._openMenu();
// the menu should close if clicking somewhere on the body (excluding clicks on the menu)
document.addEventListener( self.eventtype, function( ev ) {
if( self.open && !hasParent( ev.target, self.el.id ) ) {
bodyClickFn( this );
}
} );
}
} );
In this case, this.eventtype is 'click'.
I suspect this may have something to do with how this functionality is coded with an object. While I have decent Javascript skills, I have not had much exposure to using it in this manner.
I am instantiating the menu thusly:
new mlPushMenu(document.getElementById('mp-menu'), document.getElementById('trigger'));
I realize I could extract this method, but that seems to violate some best practices in general.
Any suggestions will be most appreciated!
You can't use this module as-is to do this. The only event types it supports are "click" and "touchstart" and its mobilecheck() method determines which one of the two it uses.
You'll either have to fake a click on a trigger element or you'll have to modify this module. You can do this with the .click() method of a DOM element. .trigger.click() probably won't do it; you would probably be better off just getting the element (via $('#trigger') or document.getElementById()) and then calling the .click() method of that.
I just tried this in Chrome with an <a> with style display:none and it followed the link so it may work for another hidden element set to trigger. It's hacky but it might be preferable to changing the module.

How can I add a css element change to an onlick event in this jquery lib?

I've got this awesome slideshow library working just fine on my site (yoinked from codrops), but since I'm shifting between different pieces of information, I want to really call out the difference by adding a CSS change so that the background color matches the color of the content in the slide. Now, this is a library, so i figure I need to add the $('body').css call into it, and not my html doc. I'm including the code below, with a note marking where I think it's supposed to go. I'm jsut not sure what the exact phrasing would be since I've never worked inside a lib before. Any suggestions would be welcome!
;( function( $, window, undefined ) {
'use strict';
// global
var Modernizr = window.Modernizr;
$.CBPFWSlider = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.CBPFWSlider.defaults = {
// default transition speed (ms)
speed : 500,
// default transition easing
easing : 'ease'
};
$.CBPFWSlider.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.CBPFWSlider.defaults, options );
// cache some elements and initialize some variables
this._config();
// initialize/bind the events
this._initEvents();
},
_config : function() {
// the list of items
this.$list = this.$el.children( 'ul' );
// the items (li elements)
this.$items = this.$list.children( 'li' );
// total number of items
this.itemsCount = this.$items.length;
// support for CSS Transitions & transforms
this.support = Modernizr.csstransitions && Modernizr.csstransforms;
this.support3d = Modernizr.csstransforms3d;
// transition end event name and transform name
var transProperties = {
'WebkitTransition' : { transitionEndEvent : 'webkitTransitionEnd', tranformName : '-webkit-transform' },
'MozTransition' : { transitionEndEvent : 'transitionend', tranformName : '-moz-transform' },
'OTransition' : { transitionEndEvent : 'oTransitionEnd', tranformName : '-o-transform' },
'msTransition' : { transitionEndEvent : 'MSTransitionEnd', tranformName : '-ms-transform' },
'transition' : { transitionEndEvent : 'transitionend', tranformName : 'transform' }
};
if( this.support ) {
this.transEndEventName = transProperties[ Modernizr.prefixed( 'transition' ) ].transitionEndEvent + '.cbpFWSlider';
this.transformName = transProperties[ Modernizr.prefixed( 'transition' ) ].tranformName;
}
// current and old item´s index
this.current = 0;
this.old = 0;
// check if the list is currently moving
this.isAnimating = false;
// the list (ul) will have a width of 100% x itemsCount
this.$list.css( 'width', 100 * this.itemsCount + '%' );
// apply the transition
if( this.support ) {
this.$list.css( 'transition', this.transformName + ' ' + this.options.speed + 'ms ' + this.options.easing );
}
// each item will have a width of 100 / itemsCount
this.$items.css( 'width', 100 / this.itemsCount + '%' );
// add navigation arrows and the navigation dots if there is more than 1 item
if( this.itemsCount > 1 ) {
// add navigation arrows (the previous arrow is not shown initially):
this.$navPrev = $( '<span class="cbp-fwprev"><</span>' ).hide();
this.$navNext = $( '<span class="cbp-fwnext">></span>' );
$( '<nav/>' ).append( this.$navPrev, this.$navNext ).appendTo( this.$el );
// add navigation dots
var dots = '';
for( var i = 0; i < this.itemsCount; ++i ) {
// current dot will have the class cbp-fwcurrent
var dot = i === this.current ? '<span class="cbp-fwcurrent"></span>' : '<span></span>';
dots += dot;
}
var navDots = $( '<div class="cbp-fwdots"/>' ).append( dots ).appendTo( this.$el );
this.$navDots = navDots.children( 'span' );
}
},
_initEvents : function() {
var self = this;
if( this.itemsCount > 1 ) {
this.$navPrev.on( 'click.cbpFWSlider', $.proxy( this._navigate, this, 'previous' ) );
this.$navNext.on( 'click.cbpFWSlider', $.proxy( this._navigate, this, 'next' ) );
this.$navDots.on( 'click.cbpFWSlider', function() { self._jump( $( this ).index() ); } );
}
},
_navigate : function( direction ) {
// do nothing if the list is currently moving
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
// update old and current values
this.old = this.current;
if( direction === 'next' && this.current < this.itemsCount - 1 ) {
++this.current;
//***I think maybe it goes here?!?
}
else if( direction === 'previous' && this.current > 0 ) {
--this.current;
//***I think maybe it goes here?!?
}
// slide
this._slide();
},
_slide : function() {
// check which navigation arrows should be shown
this._toggleNavControls();
// translate value
var translateVal = -1 * this.current * 100 / this.itemsCount;
if( this.support ) {
this.$list.css( 'transform', this.support3d ? 'translate3d(' + translateVal + '%,0,0)' : 'translate(' + translateVal + '%)' );
}
else {
this.$list.css( 'margin-left', -1 * this.current * 100 + '%' );
}
var transitionendfn = $.proxy( function() {
this.isAnimating = false;
}, this );
if( this.support ) {
this.$list.on( this.transEndEventName, $.proxy( transitionendfn, this ) );
}
else {
transitionendfn.call();
}
},
_toggleNavControls : function() {
// if the current item is the first one in the list, the left arrow is not shown
// if the current item is the last one in the list, the right arrow is not shown
switch( this.current ) {
case 0 : this.$navNext.show(); this.$navPrev.hide(); break;
case this.itemsCount - 1 : this.$navNext.hide(); this.$navPrev.show(); break;
default : this.$navNext.show(); this.$navPrev.show(); break;
}
// highlight navigation dot
this.$navDots.eq( this.old ).removeClass( 'cbp-fwcurrent' ).end().eq( this.current ).addClass( 'cbp-fwcurrent' );
},
_jump : function( position ) {
// do nothing if clicking on the current dot, or if the list is currently moving
if( position === this.current || this.isAnimating ) {
return false;
}
this.isAnimating = true;
// update old and current values
this.old = this.current;
this.current = position;
// slide
this._slide();
},
destroy : function() {
if( this.itemsCount > 1 ) {
this.$navPrev.parent().remove();
this.$navDots.parent().remove();
}
this.$list.css( 'width', 'auto' );
if( this.support ) {
this.$list.css( 'transition', 'none' );
}
this.$items.css( 'width', 'auto' );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.cbpFWSlider = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'cbpFWSlider' );
if ( !instance ) {
logError( "cannot call methods on cbpFWSlider prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for cbpFWSlider instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'cbpFWSlider' );
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'cbpFWSlider', new $.CBPFWSlider( options, this ) );
}
});
}
return this;
};
} )( jQuery, window );
Answered my own question with a little digging.
_navigate : function( direction ) {
// do nothing if the list is currently moving
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
// update old and current values
this.old = this.current;
if( direction === 'next' && this.current < this.itemsCount - 1 ) {
++this.current;
}
else if( direction === 'previous' && this.current > 0 ) {
--this.current;
}
console.log(this.current);
if(this.current == 0)
{
$('body').css('background', '#FF6A00');
}else if(this.current == 1)
{
$('body').css('background', '#595C5A');
}else if(this.current == 2)
{
$('body').css('background', '#000000');
}
// slide //AROUND HERE?
this._slide();
},

Categories