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
}
Related
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>
I have Cslider.js and want the first slide to come up the same each time, however the slides after that I would want them to come up in random order, I have looked on Stackflow, and although there is some similar, I can not get it to work for me, any help greatly appreciated, here is what I have
JS
(function( $, undefined ) {
/*
* Slider object.
*/
$.Slider = function( options, element ) {
this.$el = $( element );
this._init( options );
};
$.Slider.defaults = {
current : 0, // index of current slide
bgincrement : 80, // increment the bg position (parallax effect) when sliding
autoplay : true,// slideshow on / off
interval : 5000 // time between transitions
};
$.Slider.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Slider.defaults, options );
this.$slides = this.$el.children('div.da-slide');
this.slidesCount = this.$slides.length;
this.current = this.options.current;
if( this.current < 0 || this.current >= this.slidesCount ) {
this.current = 0;
}
this.$slides.eq( this.current ).addClass( 'da-slide-current' );
var $navigation = $( '<nav class="da-dots"/>' );
for( var i = 0; i < this.slidesCount; ++i ) {
$navigation.append( '<span/>' );
}
$navigation.appendTo( this.$el );
this.$pages = this.$el.find('nav.da-dots > span');
this.$navNext = this.$el.find('span.da-arrows-next');
this.$navPrev = this.$el.find('span.da-arrows-prev');
this.isAnimating = false;
this.bgpositer = 0;
this.cssAnimations = Modernizr.cssanimations;
this.cssTransitions = Modernizr.csstransitions;
if( !this.cssAnimations || !this.cssAnimations ) {
this.$el.addClass( 'da-slider-fb' );
}
this._updatePage();
// load the events
this._loadEvents();
// slideshow
if( this.options.autoplay ) {
this._startSlideshow();
}
},
_navigate : function( page, dir ) {
var $current = this.$slides.eq( this.current ), $next, _self = this;
if( this.current === page || this.isAnimating ) return false;
this.isAnimating = true;
// check dir
var classTo, classFrom, d;
if( !dir ) {
( page > this.current ) ? d = 'next' : d = 'prev';
}
else {
d = dir;
}
if( this.cssAnimations && this.cssAnimations ) {
if( d === 'next' ) {
classTo = 'da-slide-toleft';
classFrom = 'da-slide-fromright';
++this.bgpositer;
}
else {
classTo = 'da-slide-toright';
classFrom = 'da-slide-fromleft';
--this.bgpositer;
}
this.$el.css( 'background-position' , this.bgpositer * this.options.bgincrement + '% 0%' );
}
this.current = page;
$next = this.$slides.eq( this.current );
if( this.cssAnimations && this.cssAnimations ) {
var rmClasses = 'da-slide-toleft da-slide-toright da-slide-fromleft da-slide-fromright';
$current.removeClass( rmClasses );
$next.removeClass( rmClasses );
$current.addClass( classTo );
$next.addClass( classFrom );
$current.removeClass( 'da-slide-current' );
$next.addClass( 'da-slide-current' );
}
// fallback
if( !this.cssAnimations || !this.cssAnimations ) {
$next.css( 'left', ( d === 'next' ) ? '100%' : '-100%' ).stop().animate( {
left : '0%'
}, 1000, function() {
_self.isAnimating = false;
});
$current.stop().animate( {
left : ( d === 'next' ) ? '-100%' : '100%'
}, 1000, function() {
$current.removeClass( 'da-slide-current' );
});
}
this._updatePage();
},
_updatePage : function() {
this.$pages.removeClass( 'da-dots-current' );
this.$pages.eq( this.current ).addClass( 'da-dots-current' );
},
_startSlideshow : function() {
var _self = this;
this.slideshow = setTimeout( function() {
var page = ( _self.current < _self.slidesCount - 1 ) ? page = _self.current + 1 : page = 0;
_self._navigate( page, 'next' );
if( _self.options.autoplay ) {
_self._startSlideshow();
}
}, this.options.interval );
},
page : function( idx ) {
if( idx >= this.slidesCount || idx < 0 ) {
return false;
}
if( this.options.autoplay ) {
clearTimeout( this.slideshow );
this.options.autoplay = false;
}
this._navigate( idx );
},
_loadEvents : function() {
var _self = this;
this.$pages.on( 'click.cslider', function( event ) {
_self.page( $(this).index() );
return false;
});
this.$navNext.on( 'click.cslider', function( event ) {
if( _self.options.autoplay ) {
clearTimeout( _self.slideshow );
_self.options.autoplay = false;
}
var page = ( _self.current < _self.slidesCount - 1 ) ? page = _self.current + 1 : page = 0;
_self._navigate( page, 'next' );
return false;
});
this.$navPrev.on( 'click.cslider', function( event ) {
if( _self.options.autoplay ) {
clearTimeout( _self.slideshow );
_self.options.autoplay = false;
}
var page = ( _self.current > 0 ) ? page = _self.current - 1 : page = _self.slidesCount - 1;
_self._navigate( page, 'prev' );
return false;
});
if( this.cssTransitions ) {
if( !this.options.bgincrement ) {
this.$el.on( 'webkitAnimationEnd.cslider animationend.cslider OAnimationEnd.cslider', function( event ) {
if( event.originalEvent.animationName === 'toRightAnim4' || event.originalEvent.animationName === 'toLeftAnim4' ) {
_self.isAnimating = false;
}
});
}
else {
this.$el.on( 'webkitTransitionEnd.cslider transitionend.cslider OTransitionEnd.cslider', function( event ) {
if( event.target.id === _self.$el.attr( 'id' ) )
_self.isAnimating = false;
});
}
}
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.cslider = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'cslider' );
if ( !instance ) {
logError( "cannot call methods on cslider prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for cslider instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'cslider' );
if ( !instance ) {
$.data( this, 'cslider', new $.Slider( options, this ) );
}
});
}
return this;
};
})( jQuery );
This is what I have for HTML
<div id="da-slider" class="da-slider">
<div class="da-slide">
<h2>Dog with a bone</h2>
<p>place copy here<br />
Dwell Time</p>
Read more
<div class="da-img"><img src="images/1.png" alt="image01" /></div>
</div>
<div class="da-slide">
<h2>Easy management</h2>
<p>place copy here</p>
Read more
<div class="da-img"><img src="images/2.png" alt="image01" /></div>
</div>
<nav class="da-arrows">
<span class="da-arrows-prev"></span>
<span class="da-arrows-next"></span>
</nav>
</div>
I have looked on Stackflow and although there are a few, the code is different, and have tried to do this, but i am stumped, Any help greatly apperciated.
Sam
I came across a situation where I need to adapt a script that works with JQuery 1.7.1 to work with JQuery 1.6.1, basically I need to convert the .on() to something that works with JQuery 1.6.1
here is the code I need it be run under JQuery 1.6.1 (change .on() functions ):
(function( $, undefined ) {
/*
* Slider object.
*/
$.Slider = function( options, element ) {
this.$el = $( element );
this._init( options );
};
$.Slider.defaults = {
current : 0, // index of current slide
bgincrement : 50, // increment the bg position (parallax effect) when sliding
autoplay : false,// slideshow on / off
interval : 4000 // time between transitions
};
$.Slider.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Slider.defaults, options );
this.$slides = this.$el.children('div.da-slide');
this.slidesCount = this.$slides.length;
this.current = this.options.current;
if( this.current < 0 || this.current >= this.slidesCount ) {
this.current = 0;
}
this.$slides.eq( this.current ).addClass( 'da-slide-current' );
var $navigation = $( '<nav class="da-dots"/>' );
for( var i = 0; i < this.slidesCount; ++i ) {
$navigation.append( '<span/>' );
}
$navigation.appendTo( this.$el );
this.$pages = this.$el.find('nav.da-dots > span');
this.$navNext = this.$el.find('span.da-arrows-next');
this.$navPrev = this.$el.find('span.da-arrows-prev');
this.isAnimating = false;
this.bgpositer = 0;
this.cssAnimations = Modernizr.cssanimations;
this.cssTransitions = Modernizr.csstransitions;
if( !this.cssAnimations || !this.cssAnimations ) {
this.$el.addClass( 'da-slider-fb' );
}
this._updatePage();
// load the events
this._loadEvents();
// slideshow
if( this.options.autoplay ) {
this._startSlideshow();
}
},
_navigate : function( page, dir ) {
var $current = this.$slides.eq( this.current ), $next, _self = this;
if( this.current === page || this.isAnimating ) return false;
this.isAnimating = true;
// check dir
var classTo, classFrom, d;
if( !dir ) {
( page > this.current ) ? d = 'next' : d = 'prev';
}
else {
d = dir;
}
if( this.cssAnimations && this.cssAnimations ) {
if( d === 'next' ) {
classTo = 'da-slide-toleft';
classFrom = 'da-slide-fromright';
++this.bgpositer;
}
else {
classTo = 'da-slide-toright';
classFrom = 'da-slide-fromleft';
--this.bgpositer;
}
this.$el.css( 'background-position' , this.bgpositer * this.options.bgincrement + '% 0%' );
}
this.current = page;
$next = this.$slides.eq( this.current );
if( this.cssAnimations && this.cssAnimations ) {
var rmClasses = 'da-slide-toleft da-slide-toright da-slide-fromleft da-slide-fromright';
$current.removeClass( rmClasses );
$next.removeClass( rmClasses );
$current.addClass( classTo );
$next.addClass( classFrom );
$current.removeClass( 'da-slide-current' );
$next.addClass( 'da-slide-current' );
}
// fallback
if( !this.cssAnimations || !this.cssAnimations ) {
$next.css( 'left', ( d === 'next' ) ? '100%' : '-100%' ).stop().animate( {
left : '0%'
}, 1000, function() {
_self.isAnimating = false;
});
$current.stop().animate( {
left : ( d === 'next' ) ? '-100%' : '100%'
}, 1000, function() {
$current.removeClass( 'da-slide-current' );
});
}
this._updatePage();
},
_updatePage : function() {
this.$pages.removeClass( 'da-dots-current' );
this.$pages.eq( this.current ).addClass( 'da-dots-current' );
},
_startSlideshow : function() {
var _self = this;
this.slideshow = setTimeout( function() {
var page = ( _self.current < _self.slidesCount - 1 ) ? page = _self.current + 1 : page = 0;
_self._navigate( page, 'next' );
if( _self.options.autoplay ) {
_self._startSlideshow();
}
}, this.options.interval );
},
page : function( idx ) {
if( idx >= this.slidesCount || idx < 0 ) {
return false;
}
if( this.options.autoplay ) {
clearTimeout( this.slideshow );
this.options.autoplay = false;
}
this._navigate( idx );
},
_loadEvents : function() {
var _self = this;
this.$pages.on( 'click.cslider', function( event ) {
_self.page( $(this).index() );
return false;
});
this.$navNext.on( 'click.cslider', function( event ) {
if( _self.options.autoplay ) {
clearTimeout( _self.slideshow );
_self.options.autoplay = false;
}
var page = ( _self.current < _self.slidesCount - 1 ) ? page = _self.current + 1 : page = 0;
_self._navigate( page, 'next' );
return false;
});
this.$navPrev.on( 'click.cslider', function( event ) {
if( _self.options.autoplay ) {
clearTimeout( _self.slideshow );
_self.options.autoplay = false;
}
var page = ( _self.current > 0 ) ? page = _self.current - 1 : page = _self.slidesCount - 1;
_self._navigate( page, 'prev' );
return false;
});
if( this.cssTransitions ) {
if( !this.options.bgincrement ) {
this.$el.on( 'webkitAnimationEnd.cslider animationend.cslider OAnimationEnd.cslider', function( event ) {
if( event.originalEvent.animationName === 'toRightAnim4' || event.originalEvent.animationName === 'toLeftAnim4' ) {
_self.isAnimating = false;
}
});
}
else {
this.$el.on( 'webkitTransitionEnd.cslider transitionend.cslider OTransitionEnd.cslider', function( event ) {
if( event.target.id === _self.$el.attr( 'id' ) )
_self.isAnimating = false;
});
}
}
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.cslider = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'cslider' );
if ( !instance ) {
logError( "cannot call methods on cslider prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for cslider instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'cslider' );
if ( !instance ) {
$.data( this, 'cslider', new $.Slider( options, this ) );
}
});
}
return this;
};
})( jQuery );
Since it doesn't look like there's any event delegation happening, you should be able to directly replace .on with .bind.
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();
},
I have problem calling one method from another method in a Javascript class.
Here is the code
function Spinner( max_value , min_value , div_id ){
var MAX_VALUE = 25;
var MIN_VALUE = -25;
var DEFAULT_VALUE = 0;
this.maxValue = max_value;
this.minValue = min_value;
this.divId = div_id;
this.spinnerControl; //spinner control object that is populated in getSpinner() method.
this.rotateSpinner = function (spinnerTextBoxId,up) {
document.getElementById(spinnerTextBoxId).value = up ? parseInt(document
.getElementById(spinnerTextBoxId).value) + 1 : parseInt(document
.getElementById(spinnerTextBoxId).value) - 1;
};
this.getSpinner = function( ){
spinnerControl = $('<input type="text"></input>')
.attr('id' , 'spinner')
.attr('val' , DEFAULT_VALUE)
.add( $('<ul></ul>')
.addClass("spinner")
.append(
$('<li></li>')
.append($('<input type="button"></input>')
.attr({
id : 'upButton',
value : '▲'
}).appendTo( $('<li></li>') )
)
).append( $('<li></li>')
.append($('<input type="button"></input>')
.attr({
id : 'downButton',
value : '▼'
}).appendTo( $('<li></li>') )
)
)
);
var timeoutId = 0;
$('#upButton' , spinnerControl).mousedown(function() {
console.log('mouse down');
timeoutId = setInterval(this.rotateSpinner('spinner' , true ) , 200);
}).bind('mouseup mouseleave', function() {
console.log('mouse left');
//clearTimeout(timeoutId);
});
// $('#downButton').mousedown(function() {
// alert('herer');
// //timeoutId = setInterval("rotateSpinner('spinner' , false ) ", 200);
// }).bind('mouseup mouseleave', function() {
// clearTimeout(timeoutId);
// });
return spinnerControl;
};
//class END
}
In this js file ,the error shows up in firebug : "Reference error : rotateSpinner" is not defined.
Why is it appearing ?
this is referring the DOM-element, which in this case is the '#upButton'. If you add a variable that points to the class, you can then refer to this one instead of this when defining functions within the method.
function Spinner( max_value , min_value , div_id ){
var MAX_VALUE = 25;
var MIN_VALUE = -25;
var DEFAULT_VALUE = 0;
this.maxValue = max_value;
this.minValue = min_value;
this.divId = div_id;
this.spinnerControl; //spinner control object that is populated in getSpinner() method.
this.rotateSpinner = function (spinnerTextBoxId,up) {
document.getElementById(spinnerTextBoxId).value = up ? parseInt(document
.getElementById(spinnerTextBoxId).value) + 1 : parseInt(document
.getElementById(spinnerTextBoxId).value) - 1;
};
this.getSpinner = function( ){
var self = this;
spinnerControl = $('<input type="text"></input>')
.attr('id' , 'spinner')
.attr('val' , DEFAULT_VALUE)
.add( $('<ul></ul>')
.addClass("spinner")
.append(
$('<li></li>')
.append($('<input type="button"></input>')
.attr({
id : 'upButton',
value : '▲'
}).appendTo( $('<li></li>') )
)
).append( $('<li></li>')
.append($('<input type="button"></input>')
.attr({
id : 'downButton',
value : '▼'
}).appendTo( $('<li></li>') )
)
)
);
var timeoutId = 0;
$('#upButton' , spinnerControl).mousedown(function() {
console.log('mouse down');
timeoutId = setInterval(self.rotateSpinner('spinner' , true ) , 200);
}).bind('mouseup mouseleave', function() {
console.log('mouse left');
//clearTimeout(timeoutId);
});
// $('#downButton').mousedown(function() {
// alert('herer');
// //timeoutId = setInterval("rotateSpinner('spinner' , false ) ", 200);
// }).bind('mouseup mouseleave', function() {
// clearTimeout(timeoutId);
// });
return spinnerControl;
};
//class END
}
Depends on how you call this function.
If you call it like this:
Spinner().rotateSpinner(arg1, arg2);
You would the error you mentioned.
The right usage is:
new Spinner().rotateSpinner(arg1, arg2);
It's better you learn more about variable scope of javascript.