how to include a external js function as a internal js function? - javascript

i have external js file for circular progress bar.i dont want to have my js file as a external file.i want to have this function also as a internal js function.when i tried including this function i got function is not defined error..
below is the code..
Internal js script...
<script>
( function( $ ){
$( '#circle' ).progressCircle();
$( '#submit' ).click( function() {
$( '#circle' ).progressCircle({
nPercent : 100,
showPercentText : true,
thickness : 4,
circleSize : 50
});
})
})( jQuery );
</script>
My external js file...
( function( $ ){
var ProgressCircle = function( element, options ){
var settings = $.extend( {}, $.fn.progressCircle.defaults,
options );
var thicknessConstant = 0.02;
var nRadian = 0;
computePercent();
setThickness();
var border = ( settings.thickness * thicknessConstant ) + 'em';
var offset = ( 1 - thicknessConstant * settings.thickness * 2 ) +
'em';
var circle = $( element );
var progCirc = circle.find( '.prog-circle' );
var circleDiv = progCirc.find( '.bar' );
var circleSpan = progCirc.children( '.percenttext' );
var circleFill = progCirc.find( '.fill' );
var circleSlice = progCirc.find( '.slice' );
if ( settings.nPercent == 0 ) {
circleSlice.hide();
} else {
resetCircle();
transformCircle( nRadians, circleDiv );
}
setBorderThickness();
updatePercentage();
setCircleSize();
function computePercent () {
settings.nPercent > 100 || settings.nPercent < 0 ? settings.nPercent
= 0 : settings.nPercent;
nRadians = ( 360 * settings.nPercent ) / 100;
}
function setThickness () {
if ( settings.thickness > 10 ) {
settings.thickness = 10;
} else if ( settings.thickness < 1 ) {
settings.thickness = 1;
} else {
settings.thickness = Math.round( settings.thickness );
}
}
function setCircleSize ( ) {
progCirc.css( 'font-size', settings.circleSize + 'px' );
}
function transformCircle ( nRadians, cDiv ) {
var rotate = "rotate(" + nRadians + "deg)";
cDiv.css({
"-webkit-transform" : rotate,
"-moz-transform" : rotate,
"-ms-transform" : rotate,
"-o-transform" : rotate,
"transform" : rotate
});
if( nRadians > 180 ) {
transformCircle( 180, circleFill );
circleSlice.addClass( ' clipauto ');
}
}
function setBorderThickness () {
progCirc.find(' .slice > div ').css({
'border-width' : border,
'width' : offset,
'height' : offset
})
progCirc.find('.after').css({
'top' : border,
'left' : border,
'width' : offset,
'height' : offset
})
}
function resetCircle () {
circleSlice.show();
circleSpan.text( '' );
circleSlice.removeClass( 'clipauto' )
transformCircle( 20, circleDiv );
transformCircle( 20, circleFill );
return this;
}
function updatePercentage () {
settings.showPercentText && circleSpan.text( settings.nPercent + '%'
);
}
};
$.fn.progressCircle = function( options ) {
return this.each( function( key, value ){
var element = $( this );
if ( element.data( 'progressCircle' ) ) {
var progressCircle = new ProgressCircle( this, options );
return element.data( 'progressCircle' );
}
$( this ).append( '<div class="prog-circle">' +
' <div class="percenttext"> </div>' +
' <div class="slice">' +
' <div class="bar"> </div>' +
' <div class="fill"> </div>' +
' </div>' +
' <div class="after"> </div>' +
'</div>');
var progressCircle = new ProgressCircle( this, options );
element.data( 'progressCircle', progressCircle );
});
};
$.fn.progressCircle.defaults = {
nPercent : 50,
showPercentText : true,
circleSize : 100,
thickness : 3
};
})( jQuery );
how to integrate this external js with internal js script and make it work?

Scripts are run linearly. Therefore, if you want to access code in an external script, you'll need to reference it before your internal script.
<script src="external script path"></script>
<script>
your internal script with access to external script
</script>

Related

jQuery check for cookie on page load

This is my website.
This is the JQuery code:
(function($){
var MSG_THANK_YOU = 'Thank you for voting!';
var MSG_CANT_VOTE = "You have already voted!";
var MSG_SELECT_ONE = "Please select one option!";
//-----------------------------------------------
// showTip
//-----------------------------------------------
var period_tip_window = 3000;
function showTip( obj, txt, bgcolor )
{
txt = typeof txt !== 'undefined' ? txt : "Saved!";
bgcolor = typeof bgcolor !== 'undefined' ? bgcolor : "#60a060";
var tip_box = obj.find( 'span[ttype="tip_box"]' ).clone();
if ( !tip_box.length )
{
var s = '';
s += "<span ";
s += "style='";
s += "text-align:center;";
s += "padding:10px;";
s += "margin:10px;";
s += "font-size:15px;";
s += "font-weight:bold;";
s += "font-style:italic;";
s += "font-family:times;";
s += "color:#ffffff;";
s += "background-color:" + bgcolor + ";";
s += "border:3px solid #cfcfcf;";
s += "border-radius: 15px;";
s += "-moz-border-radius: 15px;";
s += "-moz-box-shadow: 1px 1px 3px #000;";
s += "-webkit-box-shadow: 1px 1px 3px #000;";
s += "'>";
s += txt;
s += "</span>";
tip_box = $( s );
}
tip_box.css({
"position":"absolute",
"left":"-10000px",
"top":"-10000px"
});
tip_box.appendTo( $( 'body' ) );
tip_box.show();
wt = tip_box.outerWidth(false);
ht = tip_box.outerHeight(true);
var x = obj.offset().left;
var y = obj.offset().top;
var w = obj.width();
var h = obj.height();
var ytd = 10;
var xt = x + w/2 - wt/2;
var yt = y - ht;
tip_box.css( { "left":xt + "px", "top":yt + "px" } );
tip_box.fadeOut( period_tip_window, function() {
tip_box.remove();
});
}
//----------------------------------------------------------------
// CWaitIcon
//----------------------------------------------------------------
function CWaitIcon( url_img )
{
var s = '';
s += "<img ";
s += "src='" + url_img + "'";
s += ">";
this.img = $( s );
this.img.css({
"position":"absolute",
"left":"-10000px",
"top":"-10000px"
});
this.img.hide();
this.img.appendTo( $( 'body' ) );
}
CWaitIcon.prototype =
{
show : function( e )
{
var w = 32;
var h = 32;
this.img.css( { "left":(e.pageX - w/2) + "px",
"top":(e.pageY - h/2) + "px" } );
this.img.show();
},
hide : function()
{
this.img.hide();
}
}
//----------------------------------------------------------------
// CCookie
//----------------------------------------------------------------
function CCookie()
{
}
CCookie.prototype =
{
set : function( name, value, days )
{
days = days || 365;
var date = new Date();
date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
var expires = "; expires="+date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
},
get : function( name )
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0; i < ca.length; i++ )
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
del : function( name )
{
document.cookie = name + '=; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/';
}
}
var Cookie = new CCookie();
//----------------------------------------------------------------
// CAjaxPoll
//----------------------------------------------------------------
function CAjaxPoll( domobj )
{
this.domobj = domobj;
this.form = $( domobj );
this.tid = this.getAttr( 'tid', domobj );
this.b_front = true;
var action = this.getAttr( 'action', domobj );
this.url_server = action;
var pos = action.lastIndexOf("/");
var url_image = 'wait.gif';
if ( pos != -1 )
{
var path = action.substring( 0, pos+1 );
url_image = path + 'images/' + url_image;
}
this.wait_icon = new CWaitIcon( url_image );
}
CAjaxPoll.prototype =
{
//-----------------------------------------------
// getAttr
//-----------------------------------------------
getAttr : function( id_name, obj )
{
if (
( typeof( $( obj ).attr( id_name ) ) == 'undefined' ) ||
( $( obj ).attr( id_name ) == '' ) // for Opera
) return null;
return $( obj ).attr( id_name );
},
//-----------------------------------------------
// getCookieName
//-----------------------------------------------
getCookieName : function()
{
return 'ajax_poll_' + this.tid;
},
//-----------------------------------------------
// checkCookie
//-----------------------------------------------
checkCookie : function()
{
var key = this.getCookieName();
var s = Cookie.get( key );
if ( s == null )
{
Cookie.set( key, 'yes' );
$('.ajax-poll-btn-vote').css('display','none');
return true;
}
else
return false;
},
//-----------------------------------------------
// send
//-----------------------------------------------
send : function( item_tid )
{
var _this = this;
$.post( this.url_server,
{ cmd: "vote", form_tid:this.tid, item_tid:item_tid },
function(data) {
_this.wait_icon.hide();
var res = eval('(' + data + ')');
if ( res.result == 'OK' )
{
_this.items = res.items;
_this.displayStats();
}
else
{
alert( res.result );
}
});
},
//-----------------------------------------------
// run
//-----------------------------------------------
run : function()
{
var _this = this;
//-- [BEGIN] Row mouse over
this.form.find( '.ajax-poll-item' ).mouseover( function() {
$( this ).addClass( "ajax-poll-item-mover" );
}).mouseout( function() {
$( this ).removeClass( "ajax-poll-item-mover" );
});
//-- [END] Row mouse over
//-- [BEGIN] Setup radio buttons
this.form.find( '.ajax-poll-item , .ajax-poll-item-radio' ).each( function(){
var form_tid = _this.tid;
var item_tid = $(this).attr( 'tid' );
var radio = $(this).find( '.ajax-poll-item-radio' ).eq(0);
radio.attr( 'name', form_tid );
radio.attr( 'value', item_tid );
});
//-- [END] Setup radio buttons
//-- [BEGIN] Select an item
this.form.find( '.ajax-poll-item, .ajax-poll-item-radio' ).click( function(e){
//e.preventDefault();
if ( !_this.b_front ) return;
var tid = $(this).attr( 'tid' );
var radio = $(this).find( 'input[value="' + tid + '"]' );
radio.attr( 'checked', 'checked' );
_this.form.find( '.ajax-poll-item' )
.removeClass( "ajax-poll-item-sel" );
$(this).addClass( "ajax-poll-item-sel" );
});
//-- [END] Select an item
//-- [BEGIN] Vote
this.form.find( '.ajax-poll-btn-vote' ).click( function(e){
e.preventDefault();
var form = $(this).parents( '.ajax-poll-form' ).eq(0);
var item_tid = form.find( 'input[name="' + _this.tid + '"]:checked').val();
if ( typeof(item_tid) == 'undefined' ) item_tid = '';
if ( item_tid == '' )
{
showTip( form.find( '.ajax-poll-vote-box' ),
MSG_SELECT_ONE, "#ff0000" );
return
}
else
{
if ( _this.checkCookie() )
{
showTip( form.find( '.ajax-poll-vote-box' ),
MSG_THANK_YOU );
}
else
{
showTip( form.find( '.ajax-poll-vote-box' ),
MSG_CANT_VOTE, "#ff0000" );
return;
}
}
_this.b_front = false;
form.find( '.ajax-poll-item-desc-box' ).hide();
form.find( '.ajax-poll-item-bar' ).css( 'width', 0 );
form.find( '.ajax-poll-item-count' ).html( '' );
form.find( '.ajax-poll-item-perc' ).html( '' );
form.find( '.ajax-poll-item-stats-box' ).show();
form.find( '.ajax-poll-vote-box' ).hide();
form.find('.ajax-poll-item-caption ').hide();
form.find('.ajax-poll-item-sel ').css('background','none');
form.find( '.ajax-poll-item-radio' ).hide();
_this.vote( e, item_tid );
});
//-- [END] Vote
//-- [BEGIN] View result
this.form.find( '.ajax-poll-btn-view' ).click( function(e){
e.preventDefault();
_this.b_front = false;
var form = _this.form;
form.find( '.ajax-poll-item-desc-box' ).hide();
form.find( '.ajax-poll-item-bar' ).css( 'width', 0 );
form.find( '.ajax-poll-item-count' ).html( '' );
form.find( '.ajax-poll-item-perc' ).html( '' );
form.find( '.ajax-poll-item-stats-box' ).show();
form.find( '.ajax-poll-vote-box' ).hide();
form.find('.ajax-poll-item-caption').hide();
form.find( '.ajax-poll-item-radio' ).hide();
form.find('.ajax-poll-item-sel ').css('background','none');
_this.vote( e, '' );
});
//-- [END] View result
//-- [BEGIN] Go Back
/*this.form.find( '.ajax-poll-btn-back' ).click( function(e){
e.preventDefault();
_this.b_front = true;
var form = _this.form;
form.find( '.ajax-poll-item-desc-box' ).show();
form.find( '.ajax-poll-item-stats-box' ).hide();
form.find( '.ajax-poll-vote-box' ).show();
form.find( '.ajax-poll-back-box' ).hide();
form.find( '.ajax-poll-item-radio' ).show();
});*/
//-- [END] Go Back
//-- [BEGIN] Reset cookie
/* this.form.next( '.ajax-poll-btn-reset' ).click( function(e){
e.preventDefault();
Cookie.del( _this.getCookieName() );
alert( "Cookie has been reset!" );
}); */
//-- [END] Reset cookie
},
//-----------------------------------------------
// vote
//-----------------------------------------------
vote : function( e, item_tid )
{
this.wait_icon.show(e);
this.send( item_tid );
},
//-----------------------------------------------
// displayStats
//-----------------------------------------------
displayStats : function()
{
var _this = this;
//-- [BEGIN] Calculate total & Find max count
var total = 0;
var max_cnt = 0;
this.form.find( '.ajax-poll-item' ).each( function(){
var item_tid = $(this).attr( 'tid' );
var cnt = 0;
if ( typeof(_this.items[item_tid]) != 'undefined' )
{
cnt = _this.items[item_tid];
}
else
{
_this.items[item_tid] = cnt;
}
if ( max_cnt < cnt ) max_cnt = cnt;
total += cnt;
});
this.form.find( '.ajax-poll-total-value' ).html( total.toString() + ' vote'
+ ( total == 1 ? '' : 's' ) );
//-- [END] Calculate total & Find max count
//-- [BEGIN] Find max width
var max_w = this.form
.find( '.ajax-poll-item' )
.eq(0)
.width();
max_w = parseInt( max_w );
//-- [END] Find max width
//-- [BEGIN] Show counts, percentage, and bar
this.form.find( '.ajax-poll-item' ).each( function(){
var tid = $(this).attr( 'tid' );
var cnt = ( typeof(_this.items[tid]) == 'undefined' ) ?
0 : _this.items[tid];
var perc = ( total > 0 ) ?
( ( cnt * 100 ) / total ) : 0;
$(this).find( '.ajax-poll-item-count' ).html( cnt.toString() + ' vote'
+ ( cnt == 1 ? '' : 's' ) );
$(this).find( '.ajax-poll-item-perc' ).html( perc.toFixed(1) + '%' );
if ( max_cnt > 0 )
{
var w = ( cnt * max_w ) / max_cnt;
var bar = $(this).find( '.ajax-poll-item-bar' );
bar.css( 'width', 300 );
bar.animate({
width: w
}, 1000 );
}
});
//-- [END] Show counts, percentage, and bar
}
}
//----------------------------------------------------------------
// ready
//----------------------------------------------------------------
$(document).ready(function() {
$( '.ajax-poll-form' ).each( function(){
var obj = new CAjaxPoll( this );
obj.run();
});
});
}(jQuery));
How do I first check on page load if the cookies exist for each form and if cookies exist do not display the ".ajax-poll-btn-vote " just the view button.
function getCookie(cookieName) {
var i, x, y, cookiesArray = document.cookie.split(";");
for (i = 0; i < cookiesArray.length; i++) {
x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookieName) {
return unescape(y);
}
}
}
var cookie = getCookie("yourcookiename");
if (cookie != null) {
... your code here
}

jQuery Hover out-of-line

I have a really simple JavaScript image hover script running on this website, but the hover isn't lining up with the image, and I cant for the life of me figure out why.
http://www.checkmyathletics.com/home/sample-page/
Does my error popout at anyone?
I can post anything thats needs,
thanks
;( function( $, window, undefined ) {
'use strict';
$.HoverDir = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.HoverDir.defaults = {
speed : 300,
easing : 'ease',
hoverDelay : 0,
inverse : false
};
$.HoverDir.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.HoverDir.defaults, options );
// transition properties
this.transitionProp = 'all ' + this.options.speed + 'ms ' + this.options.easing;
// support for CSS transitions
this.support = Modernizr.csstransitions;
// load the events
this._loadEvents();
},
_loadEvents : function() {
var self = this;
this.$el.on( 'mouseenter.hoverdir, mouseleave.hoverdir', function( event ) {
var $el = $( this ),
$hoverElem = $el.find( 'div' ),
direction = self._getDir( $el, { x : event.pageX, y : event.pageY } ),
styleCSS = self._getStyle( direction );
if( event.type === 'mouseenter' ) {
$hoverElem.hide().css( styleCSS.from );
clearTimeout( self.tmhover );
self.tmhover = setTimeout( function() {
$hoverElem.show( 0, function() {
var $el = $( this );
if( self.support ) {
$el.css( 'transition', self.transitionProp );
}
self._applyAnimation( $el, styleCSS.to, self.options.speed );
} );
}, self.options.hoverDelay );
}
else {
if( self.support ) {
$hoverElem.css( 'transition', self.transitionProp );
}
clearTimeout( self.tmhover );
self._applyAnimation( $hoverElem, styleCSS.from, self.options.speed );
}
} );
},
// credits : http://stackoverflow.com/a/3647634
_getDir : function( $el, coordinates ) {
// the width and height of the current div
var w = $el.width(),
h = $el.height(),
// calculate the x and y to get an angle to the center of the div from that x and y.
// gets the x value relative to the center of the DIV and "normalize" it
x = ( coordinates.x - $el.offset().left - ( w/2 )) * ( w > h ? ( h/w ) : 1 ),
y = ( coordinates.y - $el.offset().top - ( h/2 )) * ( h > w ? ( w/h ) : 1 ),
// the angle and the direction from where the mouse came in/went out clockwise (TRBL=0123);
// first calculate the angle of the point,
// add 180 deg to get rid of the negative values
// divide by 90 to get the quadrant
// add 3 and do a modulo by 4 to shift the quadrants to a proper clockwise TRBL (top/right/bottom/left) **/
direction = Math.round( ( ( ( Math.atan2(y, x) * (180 / Math.PI) ) + 180 ) / 90 ) + 3 ) % 4;
return direction;
},
_getStyle : function( direction ) {
var fromStyle, toStyle,
slideFromTop = { left : '0px', top : '-100%' },
slideFromBottom = { left : '0px', top : '100%' },
slideFromLeft = { left : '-100%', top : '0px' },
slideFromRight = { left : '100%', top : '0px' },
slideTop = { top : '0px' },
slideLeft = { left : '0px' };
switch( direction ) {
case 0:
// from top
fromStyle = !this.options.inverse ? slideFromTop : slideFromBottom;
toStyle = slideTop;
break;
case 1:
// from right
fromStyle = !this.options.inverse ? slideFromRight : slideFromLeft;
toStyle = slideLeft;
break;
case 2:
// from bottom
fromStyle = !this.options.inverse ? slideFromBottom : slideFromTop;
toStyle = slideTop;
break;
case 3:
// from left
fromStyle = !this.options.inverse ? slideFromLeft : slideFromRight;
toStyle = slideLeft;
break;
};
return { from : fromStyle, to : toStyle };
},
// apply a transition or fallback to jquery animate based on Modernizr.csstransitions support
_applyAnimation : function( el, styleCSS, speed ) {
$.fn.applyStyle = this.support ? $.fn.css : $.fn.animate;
el.stop().applyStyle( styleCSS, $.extend( true, [], { duration : speed + 'ms' } ) );
},
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.hoverdir = function( options ) {
var instance = $.data( this, 'hoverdir' );
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
if ( !instance ) {
logError( "cannot call methods on hoverdir prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for hoverdir instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'hoverdir', new $.HoverDir( options, this ) );
}
});
}
return instance;
};
} )( jQuery, window );
$(function() {
$(' #da-thumbs > li ').each( function() { $(this).hoverdir({
hoverDelay : 75
}); } );
});
I also use Modernizer (im not familiar with it, but its not paste friendly.)
Thanks a lot
Try adding a margin-top: 20px to your .da-thumbs li a div CSS, that will push it down 20px so that it will cover the image exactly.
.da-thumbs li a div {
margin-top: 20px;
}

Isotope js detect first/last child in a row

How to detect first/last child in a row via isotope js?
I want to remove margins between elements.
This is layout.` // ====================== fitRows ======================
_fitRowsReset : function() {
this.fitRows = {
x : 0,
y : 0,
height : 0
};
},
_fitRowsLayout : function( $elems ) {
var instance = this,
containerWidth = this.element.width(),
props = this.fitRows;
$elems.each( function() {
var $this = $(this),
atomW = $this.outerWidth(true),
atomH = $this.outerHeight(true);
if ( props.x !== 0 && atomW + props.x > containerWidth ) {
// if this element cannot fit in the current row
props.x = 0;
props.y = props.height;
}
// position the atom
instance._pushPosition( $this, props.x, props.y );
props.height = Math.max( props.y + atomH, props.height );
props.x += atomW;
});
},
_fitRowsGetContainerSize : function () {
return { height : this.fitRows.height };
},
_fitRowsResizeChanged : function() {
return true;
},
`
Solution is simple
// ====================== fitRows ======================
_fitRowsReset : function() {
this.fitRows = {
x : 0,
y : 0,
height : 0
};
},
_fitRowsLayout : function( $elems ) {
var instance = this,
containerWidth = this.element.width(),
props = this.fitRows;
$elems.each( function() {
var $this = $(this),
atomW = $this.outerWidth(true),
atomH = $this.outerHeight(true);
$(this).removeClass('first last');
if (props.x == 0) {
$(this).addClass('first');
$(this).prev().addClass('last');
}
if ( props.x !== 0 && atomW + props.x > containerWidth ) {
// if this element cannot fit in the current row
props.x = 0;
props.y = props.height;
$(this).addClass('first');
$(this).prev().addClass('last');
}
// position the atom
instance._pushPosition( $this, props.x, props.y );
props.height = Math.max( props.y + atomH, props.height );
props.x += atomW;
});
},
_fitRowsGetContainerSize : function () {
return { height : this.fitRows.height };
},
_fitRowsResizeChanged : function() {
return true;
},

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();
},

Why jQuery loader not working?

When my website starts loading it should display loading upto when my website gets loaded. For that I have used jQuery plugin. The following is js file
/*
* jQuery showLoading plugin v1.0
*
* Copyright (c) 2009 Jim Keller
* Context - http://www.contextllc.com
*
* Dual licensed under the MIT and GPL licenses.
*
*/
jQuery.fn.showLoading = function(options) {
var indicatorID;
var settings = {
'addClass': '',
'beforeShow': '',
'afterShow': '',
'hPos': 'center',
'vPos': 'center',
'indicatorZIndex' : 5001,
'overlayZIndex': 5000,
'parent': '',
'marginTop': 0,
'marginLeft': 0,
'overlayWidth': null,
'overlayHeight': null
};
jQuery.extend(settings, options);
var loadingDiv = jQuery('<div></div>');
var overlayDiv = jQuery('<div></div>');
//
// Set up ID and classes
//
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(loadingDiv).attr('id', 'loading-indicator-' + indicatorID );
jQuery(loadingDiv).addClass('loading-indicator');
if ( settings.addClass ){
jQuery(loadingDiv).addClass(settings.addClass);
}
//
// Create the overlay
//
jQuery(overlayDiv).css('display', 'none');
// Append to body, otherwise position() doesn't work on Webkit-based browsers
jQuery(document.body).append(overlayDiv);
//
// Set overlay classes
//
jQuery(overlayDiv).attr('id', 'loading-indicator-' + indicatorID + '-overlay');
jQuery(overlayDiv).addClass('loading-indicator-overlay');
if ( settings.addClass ){
jQuery(overlayDiv).addClass(settings.addClass + '-overlay');
}
//
// Set overlay position
//
var overlay_width;
var overlay_height;
var border_top_width = jQuery(this).css('border-top-width');
var border_left_width = jQuery(this).css('border-left-width');
//
// IE will return values like 'medium' as the default border,
// but we need a number
//
border_top_width = isNaN(parseInt(border_top_width)) ? 0 : border_top_width;
border_left_width = isNaN(parseInt(border_left_width)) ? 0 : border_left_width;
var overlay_left_pos = jQuery(this).offset().left + parseInt(border_left_width);
var overlay_top_pos = jQuery(this).offset().top + parseInt(border_top_width);
if ( settings.overlayWidth !== null ) {
overlay_width = settings.overlayWidth;
}
else {
overlay_width = parseInt(jQuery(this).width()) + parseInt(jQuery(this).css('padding-right')) + parseInt(jQuery(this).css('padding-left'));
}
if ( settings.overlayHeight !== null ) {
overlay_height = settings.overlayWidth;
}
else {
overlay_height = parseInt(jQuery(this).height()) + parseInt(jQuery(this).css('padding-top')) + parseInt(jQuery(this).css('padding-bottom'));
}
jQuery(overlayDiv).css('width', overlay_width.toString() + 'px');
jQuery(overlayDiv).css('height', overlay_height.toString() + 'px');
jQuery(overlayDiv).css('left', overlay_left_pos.toString() + 'px');
jQuery(overlayDiv).css('position', 'absolute');
jQuery(overlayDiv).css('top', overlay_top_pos.toString() + 'px' );
jQuery(overlayDiv).css('z-index', settings.overlayZIndex);
//
// Set any custom overlay CSS
//
if ( settings.overlayCSS ) {
jQuery(overlayDiv).css ( settings.overlayCSS );
}
//
// We have to append the element to the body first
// or .width() won't work in Webkit-based browsers (e.g. Chrome, Safari)
//
jQuery(loadingDiv).css('display', 'none');
jQuery(document.body).append(loadingDiv);
jQuery(loadingDiv).css('position', 'absolute');
jQuery(loadingDiv).css('z-index', settings.indicatorZIndex);
//
// Set top margin
//
var indicatorTop = overlay_top_pos;
if ( settings.marginTop ) {
indicatorTop += parseInt(settings.marginTop);
}
var indicatorLeft = overlay_left_pos;
if ( settings.marginLeft ) {
indicatorLeft += parseInt(settings.marginTop);
}
//
// set horizontal position
//
if ( settings.hPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + ((jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width())) / 2)).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'left' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(jQuery(overlayDiv).css('margin-left'))).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'right' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + (jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(settings.hPos)).toString() + 'px');
}
//
// set vertical position
//
if ( settings.vPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('top', (indicatorTop + ((jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height())) / 2)).toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'top' ) {
jQuery(loadingDiv).css('top', indicatorTop.toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'bottom' ) {
jQuery(loadingDiv).css('top', (indicatorTop + (jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('top', (indicatorTop + parseInt(settings.vPos)).toString() + 'px' );
}
//
// Set any custom css for loading indicator
//
if ( settings.css ) {
jQuery(loadingDiv).css ( settings.css );
}
//
// Set up callback options
//
var callback_options =
{
'overlay': overlayDiv,
'indicator': loadingDiv,
'element': this
};
//
// beforeShow callback
//
if ( typeof(settings.beforeShow) == 'function' ) {
settings.beforeShow( callback_options );
}
//
// Show the overlay
//
jQuery(overlayDiv).show();
//
// Show the loading indicator
//
jQuery(loadingDiv).show();
//
// afterShow callback
//
if ( typeof(settings.afterShow) == 'function' ) {
settings.afterShow( callback_options );
}
return this;
};
jQuery.fn.hideLoading = function(options) {
var settings = {};
jQuery.extend(settings, options);
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(document.body).find('#loading-indicator-' + indicatorID ).remove();
jQuery(document.body).find('#loading-indicator-' + indicatorID + '-overlay' ).remove();
return this;
};
In html file I used the script as following..
<script type="text/javascript">
$(document).ready(
function()
{
jQuery('#activity_pane').showLoading(
{
'afterShow':
function()
{
setTimeout( "jQuery('#activity_pane').hideLoading()", 3000 );
}
}
);
}
);
</script>
and my div tag is as following..
<div id="activity_pane">
Here is where we will load something via ajax.
<br />
This container <b>must</b> have an id attribute
</div>
but i am getting error as following..
TypeError: jQuery(...).showLoading is not a function
function()
Please help me to solve this issue.
Thanks in advance.
First things first.
The event below is fired after the whole content is loaded on the page:
$(document).ready()
So, why would you attach a loading window to this event as it was supposed to be shown while the page gets loaded?
Checking the plugin website, the example given is to attach it to a click event, so the loading window will popup while the AJAX call is being executed.
Unless your whole page is loaded from an AJAX call started on a click event, I'm pretty sure their example wouldn't fit your idea.

Categories