Good day,
I have cameras that are saving videos by clips on a cloud service, with a limit on N clips. In order to save more clips, I made a scrapping script that gets all my video links from the website where I can preview them. (to be executed on page load with a JS extension)
Note that these are M3U8 files.
Here is my script:
var cameraScrapper = {
playerReady: false,
videos: {},
cameraCurrent: 0,
cameras: [
'cid1', // #1
'cid2', // #3
'cid3', // #2
],
gui: function() {
return {
calendarPreviousMonth: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'navigation' )[0].getElementsByClassName( 'prev' )[0],
calendarNextMonth: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'navigation' )[0].getElementsByClassName( 'next' )[0],
calendarSelectedDate: document.getElementById( 'event_selected_date' ),
calendarMonthDays: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'month' )[0].children,
cameras: document.getElementById( 'camera_list_dropdown' ).children,
dayClips: document.getElementById( 'event_clips_wrap' ).children,
noRecords: document.getElementsByClassName( 'no_recording' )[0]
};
},
init: function() {
document.getElementById( 'hls_player' ).addEventListener( 'canplay', function() { this.playerReady = true; }.bind( this ) );
for( let i = 0; i < this.cameras.length; i++ ) {
if( window.location.href.includes( '=' + this.cameras[i] + '&' ) ) {
this.cameraCurrent = i;
break;
}
}
while( !this.gui().calendarPreviousMonth.children[0].classList.contains( 'disabled' ) ) {
this.gui().calendarPreviousMonth.click();
}
this.scrap();
},
getVideo: function( pCamera, pTimeStamp ) {
let performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {};
let requests = ( performance.getEntries() || {} );
for( let i = 0; i < requests.length; i++ ) {
if( requests[i].name.includes( '.ts?' ) ) {
if( this.videos[encodeURIComponent( requests[i].name )] === undefined ) {
this.videos[encodeURIComponent( requests[i].name )] = { 'camera': pCamera, 'timestamp': this.formatDate( pTimeStamp ) };
}
}
}
if( Object.entries( this.videos ).length > 25 ) {
this.save();
this.videos = {};
performance.clearMarks();
performance.clearMeasures()
performance.clearResourceTimings();
}
},
formatDate( pTimestamp ) {
let date = pTimestamp.split( ' ' )[0];
let time = pTimestamp.split( ' ' )[1];
let month = {
JAN: '01',
FEB: '02',
MAR: '03',
APR: '04',
MAY: '05',
JUN: '06',
JUL: '07',
AUG: '08',
SEP: '09',
OCT: '10',
NOV: '11',
DEC: '12'
}
return date.split( '.' )[2] + '-' + month[date.split( '.' )[1]] + '-' + date.split( '.' )[0] + ' ' + time;
},
sleep: function( pMs ) {
return new Promise( resolve => setTimeout( resolve, pMs ) );
},
scrap: async function() {
let scrapDays = true;
while( scrapDays ) {
for( let i = 0; i < this.gui().calendarMonthDays.length; i++ ) {
if( !this.gui().calendarMonthDays[i].classList.contains( 'is-disabled' ) && !this.gui().calendarMonthDays[i].classList.contains( 'is-expired' ) && !this.gui().calendarMonthDays[i].classList.contains( 'is-future' ) ) {
// console.log( 'day ' + this.gui().calendarMonthDays[i].innerText );
this.gui().calendarMonthDays[i].click();
let clipsLoaded = false;
if( this.gui().noRecords !== undefined ) {
clipsLoaded = !this.gui().noRecords.classList.contains( 'displayOff' )
}
while( !clipsLoaded && ( this.gui().dayClips.length == 0 ) ) {
await this.sleep( 99 );
if( this.gui().noRecords !== undefined ) {
clipsLoaded = !this.gui().noRecords.classList.contains( 'displayOff' )
}
}
// console.log( 'clips ' + this.gui().dayClips.length );
for( let j = 0; j < this.gui().dayClips.length; j++ ) {
this.playerReady = false;
this.gui().dayClips[j].children[0].click();
while( !this.playerReady ) {
await this.sleep( 99 );
}
this.getVideo( ( '' + this.cameraCurrent ), this.gui().calendarSelectedDate.innerText + ' ' + this.gui().dayClips[j].children[0].children[1].children[1].innerText );
}
}
}
if( !this.gui().calendarNextMonth.children[0].classList.contains( 'disabled' ) ) {
this.gui().calendarNextMonth.click();
} else {
scrapDays = false;
}
}
this.save();
this.sleep( 4999 );
let cameraNext = this.cameraCurrent + 1;
if( this.cameras.length >= cameraNext ) {
cameraNext = 0;
}
window.location.href = 'https://cloudcamerasservice.com/camera?no=' + this.cameras[cameraNext] + '&model=CAM';
},
save() {
let xhr = new XMLHttpRequest();
xhr.open( 'POST', 'http://localhost/videomonitoring/stack.php', true );
xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
xhr.onload = ( e ) => { /* console.log( 'saved' ); */ };
xhr.onerror = ( e ) => {};
xhr.send( 'stack=' + encodeURIComponent( JSON.stringify( this.videos ) ) );
}
};
setTimeout( function() { cameraScrapper.init() }.bind( this ), 4999 );
stack.php will handle file download from provided list, my script is mainly about getting the video links and date of recording.
But when launching my script, my browser run out of memory after 75-100 clips saved. Can you help me with this?
Not sure if it's comming from my script, indeed, I have the feeling this is due to preloading many videos on the same page.
Related
So I'm fairly new to Html/Javascript and Im trying to put together a player that takes a playlistcode from youtube and produces a Videoplayer + thumbnails.
I run it via Netbeans 8.0.2, however sometimes I get the desired results (thumbnails do load) but most of the times I get nothing.
Here is my code:
Edit: Tried it in IE, Chrome, Firefox (all up to date). Sometimes I change basicly nothing (moving a variable down 1 line and it suddenly works.. once)
<!DOCTYPE html>
<html>
<head>
<title>F this S</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a name="ytplayer"></a>
<div id="ytplayer_div2"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js"></script>
<script type="text/javascript">
var string;
var ytplayer_playlist = [ ];
var ytplayer_playitem = 0;
swfobject.addLoadEvent( ytplayer_render_player );
swfobject.addLoadEvent( ytplayer_render_playlist );
function ytplayer_render_player( )
{
swfobject.embedSWF
(
'http://www.youtube.com/v/' + ytplayer_playlist[ ytplayer_playitem ] + '&enablejsapi=1&rel=0&fs=1&version=3',
'ytplayer_div1',
'440',
'330',
'10',
null,
null,
{
allowScriptAccess: 'always',
allowFullScreen: 'true'
},
{
id: 'ytplayer_object'
}
);
}
function ytplayer_render_playlist( )
{
for ( var i = 0; i < ytplayer_playlist.length; i++ )
{
var img = document.createElement( "img" );
img.src = "http://img.youtube.com/vi/" + ytplayer_playlist[ i ] + "/default.jpg";
var a = document.createElement( "a" );
a.href = "#ytplayer";
a.onclick = (
function( j )
{
return function( )
{
ytplayer_playitem = j;
ytplayer_playlazy( 1000 );
};
}
)( i );
a.appendChild( img );
document.getElementById( "ytplayer_div2" ).appendChild( a );
}
}
function ytplayer_playlazy( delay )
{
if ( typeof ytplayer_playlazy.timeoutid !== 'undefined' )
{
window.clearTimeout( ytplayer_playlazy.timeoutid );
}
ytplayer_playlazy.timeoutid = window.setTimeout( ytplayer_play, delay );
}
function ytplayer_play( )
{
var o = document.getElementById( 'ytplayer_object' );
if ( o )
{
o.loadVideoById( ytplayer_playlist[ ytplayer_playitem ] );
}
}
function onYouTubePlayerReady( playerid )
{
var o = document.getElementById( 'ytplayer_object' );
if ( o )
{
o.addEventListener( "onStateChange", "ytplayerOnStateChange" );
o.addEventListener( "onError", "ytplayerOnError" );
}
}
function ytplayerOnStateChange( state )
{
if ( state === 0 )
{
ytplayer_playitem += 1;
ytplayer_playitem %= ytplayer_playlist.length;
ytplayer_playlazy( 5000 );
}
}
function ytplayerOnError( error )
{
if ( error )
{
ytplayer_playitem += 1;
ytplayer_playitem %= ytplayer_playlist.length;
ytplayer_playlazy( 5000 );
}
}
</script>
<button onclick="urlAusgabeFunktion()"> Go </button>
<input type="text" name="txtJob" id="PlaylistUrl" value="PLAYLIST ID HERE">
<script>
function urlAusgabeFunktion()
{
gapi.client.setApiKey('API KEY HERE ');
gapi.client.load('youtube', 'v3', function() {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: document.getElementById("PlaylistUrl").value,
maxResults: 50
});
request.execute(function(response) {
for (var i = 0; i < response.items.length; i++)
{
string = response.items[i].snippet.resourceId.videoId;
ytplayer_playlist.push(string);
}
swfobject.addLoadEvent( ytplayer_render_player );
swfobject.addLoadEvent( ytplayer_render_playlist );
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=onGoogleLoad"></script>
The javascript below enables swipe left/right navigation. For some reason, I would like to call this function using URL such as <a href="javascript:function">. Certain URL will equivalent to left swipe, while another URL will equivalent to right swipe. Is this possible?
(function( window ){
var window = window,
document = window.document,
screen = window.screen,
touchSwipeListener = function( options ) {
// Private members
var track = {
startX: 0,
endX: 0
},
defaultOptions = {
moveHandler: function( direction ) {},
endHandler: function( direction ) {},
minLengthRatio: 0.3
},
getDirection = function() {
return track.endX > track.startX ? "prev" : "next";
},
isDeliberateMove = function() {
var minLength = Math.ceil( screen.width * options.minLengthRatio );
return Math.abs(track.endX - track.startX) > minLength;
},
extendOptions = function() {
for (var prop in defaultOptions) {
if ( defaultOptions.hasOwnProperty( prop ) ) {
options[ prop ] || ( options[ prop ] = defaultOptions[ prop ] );
}
}
},
handler = {
touchStart: function( event ) {
// At least one finger has touched the screen
if ( event.touches.length > 0 ) {
track.startX = event.touches[0].pageX;
}
},
touchMove: function( event ) {
if ( event.touches.length > 0 ) {
track.endX = event.touches[0].pageX;
options.moveHandler( getDirection(), isDeliberateMove() );
}
},
touchEnd: function( event ) {
var touches = event.changedTouches || event.touches;
if ( touches.length > 0 ) {
track.endX = touches[0].pageX;
isDeliberateMove() && options.endHandler( getDirection() );
}
}
};
extendOptions();
// Graceful degradation
if ( !document.addEventListener ) {
return {
on: function() {},
off: function() {}
}
}
return {
on: function() {
document.addEventListener('touchstart', handler.touchStart, false);
document.addEventListener('touchmove', handler.touchMove, false);
document.addEventListener('touchend', handler.touchEnd, false);
},
off: function() {
document.removeEventListener('touchstart', handler.touchStart);
document.removeEventListener('touchmove', handler.touchMove);
document.removeEventListener('touchend', handler.touchEnd);
}
}
}
// Expose global
window.touchSwipeListener = touchSwipeListener;
}( window ));
(function( window ){
var document = window.document,
// Element helpers
Util = {
addClass: function( el, className ) {
el.className += " " + className;
},
hasClass: function( el, className ) {
var re = new RegExp("\s?" + className, "gi");
return re.test( el.className );
},
removeClass: function( el, className ) {
var re = new RegExp("\s?" + className, "gi");
el.className = el.className.replace(re, "");
}
},
swipePageNav = (function() {
// Page sibling links like <link rel="prev" title=".." href=".." />
// See also http://diveintohtml5.info/semantics.html
var elLink = {
prev: null,
next: null
},
// Arrows, which slide in to indicate the shift direction
elArrow = {
prev: null,
next: null
},
swipeListener;
return {
init: function() {
this.retrievePageSiblings();
// Swipe navigation makes sense only if any of sibling page link available
if ( !elLink.prev && !elLink.next ) {
return;
}
this.renderArows();
this.syncUI();
},
syncUI: function() {
var that = this;
// Assign handlers for swipe "in progress" / "complete" events
swipeListener = new window.touchSwipeListener({
moveHandler: function( direction, isDeliberateMove ) {
if ( isDeliberateMove ) {
if ( elArrow[ direction ] && elLink[ direction ] ) {
Util.hasClass( elArrow[ direction ], "visible" ) ||
Util.addClass( elArrow[ direction ], "visible" );
}
} else {
Util.removeClass( elArrow.next, "visible" );
Util.removeClass( elArrow.prev, "visible" );
}
},
endHandler: function( direction ) {
that[ direction ] && that[ direction ]();
}
});
swipeListener.on();
},
retrievePageSiblings: function() {
elLink.prev = document.querySelector( "head > link[rel=prev]");
elLink.next = document.querySelector( "head > link[rel=next]");
},
renderArows: function() {
var renderArrow = function( direction ) {
var div = document.createElement("div");
div.className = "spn-direction-sign " + direction;
document.getElementsByTagName( "body" )[ 0 ].appendChild( div );
return div;
}
elArrow.next = renderArrow( "next" );
elArrow.prev = renderArrow( "prev" );
},
// When the shift (page swap) is requested, this overlay indicates that
// the current page is frozen and a new one is loading
showLoadingScreen: function() {
var div = document.createElement("div");
div.className = "spn-freezing-overlay";
document.getElementsByTagName( "body" )[ 0 ].appendChild( div );
},
// Request the previous sibling page
prev: function() {
if ( elLink.prev ) {
this.showLoadingScreen();
window.location.href = elLink.prev.href;
}
},
// Request the next sibling page
next: function() {
if ( elLink.next ) {
this.showLoadingScreen();
window.location.href = elLink.next.href;
}
}
}
}())
// Apply when document is ready
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
try {
swipePageNav.init();
} catch (e) {
alert(e);
}
}, false );
}( window ));
You cannot do that. However, if it is for organization goals why not have two JavaScript files, each one with its own namespace. If you do this, you call only that namespace expected for the link clicked.
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
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
}
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.