Images and buttons not loading every time - javascript

I am new to JavaScript. I created the webpage linked below as an exercise for a class I am taking.
JavaScript Product Catalog
It seems to work ok if it all loads correctly, but half the time either the images or buttons do not load, and sometimes the thumbnail loads but the full-size (mouseover) image does not load. In Firefox or IE, it seems to only happen on first loads, and after that (as long as browser stays open), it will successfully load every time after that. But in Chrome it continues to act random every single page reload. Just refresh the page about 10 times in a row and you will probably see a couple instances where either the buttons or the images (or both) don't load.
I am assuming this is a problem with my code, since I've never had any other problems with the server. Any ideas?
Thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<style type = "text/css">
.box { border: 1px solid black; padding: 4px }
</style>
<title>Product Catalog</title>
<script>
var catalogDiv;
var summaryRequest;
var descriptionsRequest;
var thumbsRequest;
var imagesRequest;
function showLargeImage( imageElement )
{
imageElement.style.display = "none";
imageElement.nextSibling.style.display = "inline";
}
function showThumb( imageElement )
{
imageElement.style.display = "none";
imageElement.previousSibling.style.display = "inline";
}
function showDesc( descButton )
{
if ( descButton.nextSibling.style.display == "none" ) {
descButton.nextSibling.style.display = "block";
} else {
descButton.nextSibling.style.display = "none";
}
}
function getDescriptions()
{
try
{
descriptionsRequest = new XMLHttpRequest();
descriptionsRequest.addEventListener("readystatechange",
loadDescriptions, false );
descriptionsRequest.open( "GET", "descriptions.json", true );
descriptionsRequest.setRequestHeader( "Accept",
"application/json; charset=utf-8" );
descriptionsRequest.send();
}
catch ( exception )
{
alert( "Request Failed" );
}
}
function loadDescriptions()
{
if ( descriptionsRequest.readyState == 4
&& descriptionsRequest.status == 200 )
{
var descriptions = JSON.parse( descriptionsRequest.responseText );
for ( var i = 0; i < descriptions.length; i++ ) {
var infoDiv = document.getElementById( descriptions[i].id +
"-info-inner" );
var descButton = document.createElement( "button" );
infoDiv.appendChild( descButton );
descButton.type = "button";
descButton.textContent = "show description";
descButton.setAttribute( "onclick", "showDesc( this )");
var desc = document.createElement( "fieldset" );
desc.style.display = "none";
desc.style.margin = "10px";
infoDiv.appendChild( desc );
desc.innerHTML = "<br>" + descriptions[i].text + "<br><br>" ;
}
}
}
function getImages()
{
try
{
imagesRequest = new XMLHttpRequest();
imagesRequest.addEventListener("readystatechange",
loadImages, false );
imagesRequest.open( "GET", "images.json", true );
imagesRequest.setRequestHeader( "Accept",
"application/json; charset=utf-8" );
imagesRequest.send();
}
catch ( exception )
{
alert( "Request Failed" );
}
}
function loadImages()
{
if ( imagesRequest.readyState == 4 && imagesRequest.status == 200 )
{
var images = JSON.parse( imagesRequest.responseText );
for ( var i = 0; i < images.length; i++ ) {
var imageDiv = document.getElementById( images[i].id +
"-image-inner" );
imageDiv.innerHTML += "<img style=\"display:none;\"" +
"src=\"" + images[i].filename+ "\">";
imageDiv.lastChild.setAttribute( "onmouseout",
"showThumb( this )" );
}
}
}
function getThumbs()
{
try
{
thumbsRequest = new XMLHttpRequest();
thumbsRequest.addEventListener("readystatechange",
loadThumbs, false );
thumbsRequest.open( "GET", "thumbs.json", true );
thumbsRequest.setRequestHeader( "Accept",
"application/json; charset=utf-8" );
thumbsRequest.send();
}
catch ( exception )
{
alert( "Request Failed" );
}
}
function loadThumbs()
{
if ( thumbsRequest.readyState == 4 && thumbsRequest.status == 200 )
{
var thumbs = JSON.parse( thumbsRequest.responseText );
for ( var i = 0; i < thumbs.length; i++ ) {
var imageDiv = document.getElementById( thumbs[i].id +
"-image-inner" );
imageDiv.innerHTML = "<img style=\"display:inline;\"" +
"src=\"" + thumbs[i].filename+ "\">";
imageDiv.firstChild.setAttribute( "onmouseover",
"showLargeImage( this )");
}
}
}
function setupDivsRequest()
{
try
{
summaryRequest = new XMLHttpRequest();
summaryRequest.addEventListener("readystatechange",
setupDivsResponse, false );
summaryRequest.open( "GET", "summary.json", true );
summaryRequest.setRequestHeader( "Accept",
"application/json; charset=utf-8" );
summaryRequest.send();
}
catch ( exception )
{
alert( "Request Failed" );
}
}
function setupDivsResponse()
{
if ( summaryRequest.readyState == 4 && summaryRequest.status == 200 )
{
var summary = JSON.parse( summaryRequest.responseText );
for ( var i = 0; i < summary.length; i++ ) {
var productDiv = document.createElement( "div" );
var productImageOuterDiv = document.createElement( "div" );
var productImageInnerDiv = document.createElement( "div" );
var productInfoOuterDiv = document.createElement( "div" );
var productInfoInnerDiv = document.createElement( "div" );
catalogDiv.appendChild(productDiv);
productDiv.appendChild( productImageOuterDiv );
productDiv.appendChild( productInfoOuterDiv );
productImageOuterDiv.appendChild( productImageInnerDiv );
productInfoOuterDiv.appendChild( productInfoInnerDiv );
productDiv.id = summary[i].id;
productDiv.className = "box";
productImageOuterDiv.id = summary[i].id + "-image-outer";
productImageOuterDiv.style.cssFloat = "left";
productImageInnerDiv.id = summary[i].id + "-image-inner";
productImageInnerDiv.style.height = "250px";
productImageInnerDiv.style.width = "250px";
productImageInnerDiv.style.display = "table-cell";
productImageInnerDiv.style.verticalAlign = "middle";
productImageInnerDiv.style.textAlign = "center";
productInfoOuterDiv.id = summary[i].id + "-info-outer";
productInfoOuterDiv.style.height = "250px";
productInfoInnerDiv.id = summary[i].id + "-info-inner";
productInfoInnerDiv.style.float = "left";
productInfoInnerDiv.style.padding = "10px";
productInfoInnerDiv.innerHTML = summary[i].title + "<br>";
productInfoInnerDiv.innerHTML += summary[i].price + "<br><br>";
}
}
}
function start()
{
catalogDiv = document.getElementById( "catalog" );
setupDivsRequest();
getThumbs();
getImages();
getDescriptions();
}
window.addEventListener( "load", start, false );
</script>
</head>
<body>
<h1>Mouse over a product thumbnail for a larger picture.</h1>
<div id = "catalog"></div>
</body>
</html>

It took a long time, but I finally got to the bottom of this problem. It was a race condition between multiple asynchronous requests to populate the same element. I had not considered this was possible, so the one which I expected to go first would add the first HTML to the element:
element.innerHTML = "first text";
While the request which I expected to go second would add the second HTML:
element.innerHTML += "second text";
Obviously if those requests go out of order, because of the way I used = and +=, the result will be that "second text" gets overwritten, which is essentially why my images weren't loading half the time. (Even if I had used += in both cases, I'd still have the problem of randomly ordered elements as my code below shows).
For whatever reason, the race condition never seemed to matter in Firefox or IE. Maybe there is something in those browsers to try to safeguard against such a condition, by forcing requests to finish in the order they started? Or maybe it is just dumb luck. But in Chrome, the requests would consistently finish in a random order. A much simpler code below illustrates clearly. In Chrome, half the time you will get "FOOBAR" as HTML output, but the other half of the time you will get "BARFOO." The testx.json files I reference in the script are dummy (empty) files.
The race condition is easily fixed in this situation by having my second setup function called by the first setup's callback function after completing its other tasks. In a more complicated situation I would guess the other typical race condition safeguards (mutexes and semaphores) would work as well.
<!DOCTYPE html>
<html>
<head>
<script>
var testDiv;
var request1;
var request2;
window.addEventListener( "load", start, false );
function start()
{
testDiv = document.getElementById( "test-div" );
setup1();
setup2();
}
function setup1()
{
try
{
request1 = new XMLHttpRequest();
request1.addEventListener("readystatechange",
response1, false );
request1.open( "GET", "test1.json", true );
request1.setRequestHeader( "Accept",
"application/json; charset=utf-8" );
request1.send();
}
catch ( exception )
{
alert( "Request Failed" );
}
}
function response1()
{
if ( request1.readyState == 4 && request1.status == 200 )
{
testDiv.innerHTML += "FOO";
}
}
function setup2()
{
try
{
request2 = new XMLHttpRequest();
request2.addEventListener("readystatechange",
response2, false );
request2.open( "GET", "test2.json", true );
request2.setRequestHeader( "Accept",
"application/json; charset=utf-8" );
request2.send();
}
catch ( exception )
{
alert( "Request Failed" );
}
}
function response2()
{
if ( request2.readyState == 4 && request2.status == 200 )
{
testDiv.innerHTML += "BAR";
}
}
</script>
</head>
<body>
<div id = "test-div"> </div>
</body>
</html>

Related

JQuery local variables in anonymous function lakes

I am not sure so I decide to ask here. I have a plugin which uses jquery animate function and then it call complete callback. It works pretty much with dom. After few cycles script starts to be slow. I cant find any issue only local lambda variables. But I dont know why this local variables should remain in memory. It does not make sense. Here is the code:
cEl.el.animate( { left: offset.left - state.cEl.mL, top: offset.top - state.cEl.mT }, 250,
function() // complete callback
{
tidyCurrEl( cEl );
targetEl.after( cEl.el[0] );
targetEl[0].style.display = 'none';
hintStyle.display = 'none';
hintNode.remove();
......
if ( isHintTarget )
{
// This seems to be a problem.
var paretnLi = state.placeholderNode.parent().closest( 'li' )
......
}
else
{
......
}
} );
Am I right the local variables in anonymous function is the problem? Thanks.
Here is full code example
function endDrag( e )
{
var cEl = state.cEl,
hintNode = $( '#s-l-hint', state.rootEl.el ),
hintStyle = hint[0].style,
targetEl = null, // hintNode/placeholderNode
isHintTarget = false, // if cEl will be placed to the hintNode
hintWrapperNode = $( '#s-l-hint-wrapper' );
if ( hintStyle.display == 'block' && hintNode.length && state.isAllowed )
{
targetEl = hintNode;
isHintTarget = true;
}
else
{
targetEl = state.placeholderNode;
isHintTarget = false;
}
offset = targetEl.offset();
cEl.el.animate( { left: offset.left - state.cEl.mL, top: offset.top - state.cEl.mT }, 250,
function() // complete callback
{
tidyCurrEl( cEl );
targetEl.after( cEl.el[0] );
targetEl[0].style.display = 'none';
hintStyle.display = 'none';
// This has to be document node, not hint as a part of documentFragment.
hintNode.remove();
hintWrapperNode
.removeAttr( 'id' )
.removeClass( setting.hintWrapperClass );
if ( hintWrapperNode.length )
{
hintWrapperNode.prev( 'div' ).append( opener.clone( true ) );
}
var placeholderNode = state.placeholderNode;
// Directly removed placeholder looks bad. It jumps up if the hint is below.
if ( isHintTarget )
{
placeholderNode.slideUp( 150, function()
{
var placeholderParent = placeholderNode.parent();
var placeholderParentLi = ( ! placeholderParent.is( state.rootEl.el ) ) ? placeholderParent.closest( 'li' ) : null;
placeholderNode.remove();
tidyEmptyLists();
setting.onChange( cEl.el );
setting.complete( cEl.el ); // Have to be here cause is necessary to remove placeholder before complete call.
state.isDragged = false;
if( setting.maxLevels !== false ) // Has to be after placeholder remove.
{
recountLevels( cEl.el );
if( placeholderParentLi ) recountLevels( placeholderParentLi );
}
});
}
else
{
state.placeholderNode.remove();
tidyEmptyLists();
setting.complete( cEl.el );
state.isDragged = false;
}
} );
scrollStop( state );
state.doc
.unbind( "mousemove", dragging )
.unbind( "mouseup", endDrag );
}

CKEdidor return multiple selected files

I am using CKFinder 3 in a Web project as described on the CKFinder Website my problem is that I can't return multiple selected Images. The problem is that when I select multiple Images just the first one is returned.
Is there a way to return multiple files?
var button1 = document.getElementById( 'ckfinder-popup-1' );
var button2 = document.getElementById( 'ckfinder-popup-2' );
button1.onclick = function() {
selectFileWithCKFinder( 'ckfinder-input-1' );
};
button2.onclick = function() {
selectFileWithCKFinder( 'ckfinder-input-2' );
};
function selectFileWithCKFinder( elementId ) {
CKFinder.modal( {
chooseFiles: true,
width: 800,
height: 600,
onInit: function( finder ) {
finder.on( 'files:choose', function( evt ) {
var file = evt.data.files.first();
var output = document.getElementById( elementId );
output.value = file.getUrl();
} );
finder.on( 'file:choose:resizedImage', function( evt ) {
var output = document.getElementById( elementId );
output.value = evt.data.resizedUrl;
} );
}
} );
I have found a way how to do it.
The only bummer is that you can’t resize images.
var button1 = document.getElementById( 'ckfinder-popup-1' );
button1.onclick = function() {
selectFileWithCKFinder( 'ckfinder-input-1' );
};
function selectFileWithCKFinder( elementId ) {
CKFinder.modal( {
chooseFiles: true,
width: 800,
height: 600,
onInit: function( finder ) {
finder.on( 'files:choose', function( evt ) {
var url='';
for(i = 0; i < evt.data.files.models.length ; i++){
var file = evt.data.files.models[i];
var tempurl = file.getUrl();
url +=','+tempurl;
}
var output = document.getElementById( elementId );
output.value = url;
} );
finder.on( 'file:choose:resizedImage', function( evt ) {
var url='';
for(i = 0; i < evt.data.files.models.length ; i++){
var file = evt.data.files.models[i];
var tempurl = file.getUrl();
url +=','+tempurl;
}
var output = document.getElementById( elementId );
output.value = url;
} );
}
} );
}
</script> ```

Html5/Javascript works in mysterious ways?

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>

how to create an ajax request when server file(like php) doesnt exist?

i was developing sharetronix script but there is something realy odd about this script i can see in console network request goes for example for this address
http://localhost/ajax/postform-submit/ajaxtp:xml/r:0
but i cant find any folder with postform-submit name.i know this is possible with redirection using htaccess but i cant find anything in htaccess file.
this is part of js code where this request send
function postform_submit_step4()
{
var req = ajax_init(true);
if( ! req ) { return; }
var p = "post_temp_id="+encodeURIComponent(pf_data.temp_id)+"&message="+encodeURIComponent(pf_data.message);
if( pf_data.existing_post_id != "" ) {
p += "&editpost="+encodeURIComponent(pf_data.existing_post_id);
}
else if( pf_data.share_with_type == "user" ) {
p += "&username="+encodeURIComponent(pf_data.share_with_xtra);
}
else if( pf_data.share_with_type == "group" ) {
p += "&groupname="+encodeURIComponent(pf_data.share_with_xtra);
}
if( pf_data.at_link[0] ) {
p += "&at_link="+encodeURIComponent(pf_data.at_link[0]);
}
if( pf_data.at_image[0] ) {
p += "&at_image="+encodeURIComponent(pf_data.at_image[0]);
}
if( pf_data.at_file[0] ) {
p += "&at_file="+encodeURIComponent(pf_data.at_file[0]);
}
if( pf_data.at_videoembed[0] ) {
p += "&at_videoembed="+encodeURIComponent(pf_data.at_videoembed[0]);
}
req.onreadystatechange = function() {
if( req.readyState != 4 ) { return; }
if( ! req.responseXML ) { return; }
var data = req.responseXML.getElementsByTagName("result");
if( !data || !data[0] ) { return; }
data = data[0];
var status = data.getElementsByTagName("status");
var message = data.getElementsByTagName("message");
if( !status || !status[0] || !message || !message[0] ) {
return;
}
status = status[0].firstChild.nodeValue;
message = message[0].firstChild.nodeValue;
if( status != "OK" ) {
d.getElementById("pf_postederror_msg").innerHTML = message;
postform_htmlobject_hide("pf_posting");
postform_htmlobject_show("pf_postederror", 36);
postform_htmlobject_show("pf_mainpart", 114, function() { pf_open_state=1; pf_post_state=3; d.post_form.message.disabled=false; d.post_form.message.focus(); });
return;
}
d.getElementById("pf_postedok_msg").innerHTML = message;
postform_htmlobject_hide("pf_posting");
postform_htmlobject_show("pf_postedok", 36, function() { pf_open_state=0; pf_post_state=1; postform_statusmsg_setTimeout(); });
var btn = d.getElementById("postform_open_button");
if(btn) {
btn.style.display = "";
}
if( posts_synchronize ) {
posts_synchronize();
}
var pinf = pf_data.existing_post_id;
if( pinf != "" ) {
pinf = pinf.split("_");
var tmp = w.location.href.toString();
tmp = tmp.replace(/^http(s)?\:\/\//, "");
tmp = tmp.substr(tmp.indexOf("/"));
var mtch = "/view/"+(pinf[0]=="public"?"post":"priv")+":"+pinf[1];
if( tmp.substr(0,mtch.length)==mtch ) {
if( viewpost_synchronize ) {
viewpost_synchronize();
}
else {
w.location.href = w.location.href.toString();
}
}
}
}
req.open("POST", siteurl+"ajax/postform-submit/ajaxtp:xml/r:"+Math.round(Math.random()*1000), true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(p);
}
how is this possible when there is no redirection?
The script is not odd: the way an URL maps to a file not always is so straightforward.
Most web frameworks, for example, use a router/dispatcher to decide what to do/which file to serve given a specific URL.
For example, most MVC web frameworks by default would handle this URL:
http://www.example.com/users/edit/5
by calling the action/method "edit" of the controller "users" passing an argument 5.
Long story short, redirects are not the only way an URL can be mapped to a physical file on the webserver.
To find which file is served or which file contains the code that is executed to produce what you receive, you first need to know which application server/framework is used, and learn how it works.

Background switcher

Hi everyone I'm having an issue that I can't seem to wrap my head around. I'll try to keep this as brief as possible.
I'm attempting to set and get cookies in the background switcher I'm using. The switcher works well... It iterates through 7 background themes on click and the cookies seem to be working as well, but still on page refresh it reverts back to to the default "theme". I don't think it's a problem with the cookies because according to the alerts I attached to the cookies, it's returning the correct background (in the alert). It's just not loading the correct theme even though the cookie says it is.
I believe I narrowed it down to a bit of code in my javascript that might be responsible for the wrong background, however I don't know how to adjust it to make it do what I want.
The background (on refresh) will be whatever var current says it will be. Values of 0-6 will be a new background (on refresh) depending on what value it is. But it doesn't remember the user's selection on refresh. I've tried making var current into an array var current = [0,1,2,3,4,5,6],, but that didn't seem to help. When I did that it didn't show any of my 7 themes, and only showed the default color in body tag css.
When I tried the array, I changed this:
if( current < pagesCount - 1 ) {
++current;
alert($.cookie('style', current, { expires: 365, path: '/' }));
}
else {
current = 0;
}
to this:
for(var i = 0; i < current.length; i++){
if( current < pagesCount - 1 ) {
++current;
alert($.cookie('style', current, { expires: 365, path: '/' }));
}
else {
current = 0;
}
}
This is the click function, but I didn't change anything here
$iterate.on( 'click', function() {
if( isAnimating ) {
return false;
}
nextPage( animcursor);
++animcursor;
} );
I'm still pretty inexperienced with javascript so I'm sure there's a better way to do what I'm trying for. Any help would be appreciated! Thanks in advance.
The entire code block:
var changeTheme = (function() {
var $main = $( '#bg-main' ),
$pages = $main.children( 'div.bg-page' ),
$iterate = $( '#iterateEffects' ),
animcursor = 1,
pagesCount = $pages.length,
current = 0,
isAnimating = false,
endCurrPage = false,
endNextPage = false,
animEndEventNames = {
'WebkitAnimation' : 'webkitAnimationEnd',
'OAnimation' : 'oAnimationEnd',
'msAnimation' : 'MSAnimationEnd',
'animation' : 'animationend'
},
// animation end event name
animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ],
// support css animations
support = Modernizr.cssanimations;
function init() {
$pages.each( function() {
var $page = $( this );
$page.data( 'originalClassList', $page.attr( 'class' ) );
} );
$pages.eq( current ).addClass( 'bg-page-current' );
$iterate.on( 'click', function() {
if( isAnimating ) {
return false;
}
nextPage( animcursor);
++animcursor;
} );
}
function nextPage( animation ) {
if( isAnimating ) {
return false;
}
isAnimating = true;
var $currPage = $pages.eq( current );
if( current < pagesCount - 1 ) {
++current;
alert($.cookie('style', current, { expires: 365, path: '/' }));
}
else {
current = 0;
}
var $nextPage = $pages.eq( current ).addClass( 'bg-page-current' ),
outClass = '', inClass = '';
outClass = 'bg-page-scaleDown';
inClass = 'bg-page-scaleUpDown bg-page-delay300';
var classes = ['bg-page-0 bg-page-current','bg-page-1 bg-page-current', 'bg-page-2 bg-page-current', 'bg-page-3 bg-page-current', 'bg-page-4 bg-page-current', 'bg-page-5 bg-page-current', 'bg-page-6 bg-page-current'];
$currPage.addClass( outClass ).on( animEndEventName, function() {
$currPage.off( animEndEventName );
endCurrPage = true;
if( endNextPage ) {
onEndAnimation( $currPage, $nextPage );
}
} );
$nextPage.addClass( inClass ).on( animEndEventName, function() {
$nextPage.off( animEndEventName );
endNextPage = true;
if( endCurrPage ) {
onEndAnimation( $currPage, $nextPage );
}
} );
if( !support ) {
onEndAnimation( $currPage, $nextPage );
}
}
function onEndAnimation( $outpage, $inpage ) {
endCurrPage = false;
endNextPage = false;
resetPage( $outpage, $inpage );
isAnimating = false;
}
function resetPage( $outpage, $inpage ) {
$outpage.attr( 'class', $outpage.data( 'originalClassList' ) );
$inpage.attr( 'class', $inpage.data( 'originalClassList' ) + ' bg-page-current' );
}
//Cookies
window.onload = function(e) {
if($.cookie('style') == undefined) {
alert($.cookie('style', current, { expires: 365, path: '/' }));
current = 0;
} else {
current = current;
alert($.cookie('style'));
}
}
init();
return { init : init };
})();
If this hits the 'else' portion of the if statement, current is not defined on page load. I think you'd need do do something like
current = $.cookie('style');
Or is it always reporting as undefined on page load?
I'd just of made a comment, but lack of rep points prevents this.
//Cookies
window.onload = function(e) {
if($.cookie('style') == undefined) {
alert($.cookie('style', current, { expires: 365, path: '/' }));
current = 0;
} else {
current = current;
alert($.cookie('style'));
}
}

Categories