Javascripts code stops working - javascript

the problem it's about a roulette that spins every 1 min,
Problem : When I switch from one tab to another on google chrome or any other navigators, the script stops running and the roulette stops (and I need to go back to the tab again in order to make the script work)
image roulette = animation of game
//<![CDATA[
var myRoll = {
nbr : [14, 1, 13, 2, 12, 3, 11, 0, 4, 10, 5, 9, 6, 8 ,7],
initRoll : function(){
var Ccolor;
var nbrCtn = $(".nbr-ctn");
for(j = 0; j < 6 ; j++){
for(i = 0; i < this.nbr.length; i++){
Ccolor = "";
if(this.nbr[i] === 0 ){
Ccolor = "nbr-green";
}else if(this.nbr[i] > 7){
Ccolor = "nbr-black";
}else{
Ccolor = "nbr-red";
}
var elem = '<div class="nbr '+ Ccolor +'" >'+ this.nbr[i] +'</div>';
nbrCtn.append(elem);
}
}
},
lastResult : function(n){
Ccolor = "";
if(n === 0 ){
Ccolor = "nbr nbr-green";
}else if(n > 7){
Ccolor = "nbr nbr-black";
}else{
Ccolor = "nbr nbr-red";
}
var nbrResult = $(".lastResult > div").length;
if(nbrResult === 5 ){
$(".lastResult div:first-child").remove();
}
var elem = '<div class="circle '+ Ccolor +'" >'+ n +'</div>';
$(".lastResult").append(elem);
},
rollAnimation : function(offset, n){
var prog = $(".progress-line");
if(offset){
prog.width("100%");
var nbrCtn = $(".nbr-ctn");
nbrCtn.css("left" , "0px");
nbrCtn.animate({left: "-"+ offset +".5px"}, 6000, 'easeInOutQuint', function(){
myRoll.lastResult(n);
myRoll.countDown();
});
}
},
getRandomInt : function(min, max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
},
startRoll : function(n){
var nbrCtn = $(".nbr-ctn");
var gAnim = $("#game-animation");
var idx = this.nbr.indexOf(n) + this.nbr.length * 4;
var elmWidth = nbrCtn.find(".nbr").width();
var offset = idx * elmWidth - (gAnim.width() / 2);
offset = this.getRandomInt(offset + 5, offset + elmWidth - 5);
this.rollAnimation(offset, n);
},
countDown : function(){
var prog = $(".progress-line");
var gameStatus = $(".rolling > span");
prog.animate({width : "0px"}, {
duration: 30000,
step: function(now){
var rt = (now*3) / 100;
gameStatus.html("Closing in " + rt.toFixed(2));
},
complete: function(){
// when the progress bar be end
gameStatus.html("Rolling ...");
myRoll.startRoll(myRoll.getRandomInt(0, 14));
},
easing: "linear"
});
}
};
window.onload = function(){
myRoll.initRoll();
myRoll.countDown();
};
//]]>

For this you need to implement things in following way (this is just way out).
Basic concept behind bellow code is calculate lag between tab switch and set current state accordingly.
var prevTime,curTime;
var rate = 500; //(miliseconds) you can set it.
function update()
{
var diffTime = curTime - prevTime;
if (diffTime >= rate)
{
//check if difference is more than step value then calculate
//current state accordingly. so you will always be updated as you calculating lags.
// e.g. diffTime = 1500;
// you will need to jump Math.floor(diffTime/rate) which is 3.
// calculate current state.
//your code....
prevTime = curTime;
}
requestAnimationFrame(update);
}

Related

Insert two scripts in the same <script> tag without conflicts

I have to put these two scripts in a single tag without them coming into conflict but I can not make it. Please, how can I do it?
Also is it better to insert multiple scripts in the same tag?
Script 1
var sec = 04;
var hour = 00;
var time0, time1;
var delay=0;
var duringtime = 1000;
time1 = (hour *10000 + min * 100 + parseInt(sec)).toString();
console.log("time1", time1);
function refresh() {
........
}
}
refresh();
Script 2
var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (max - min)) + min;
if (localStorage.getItem("stockcount_99")) {
if (localStorage.getItem("stockcount_99") >= duration) {
var value = random;
} else {
var value = localStorage.getItem("stockcount_99");
}
} else {
var value = random;
}
document.getElementById('divCounter').innerHTML = value;
var stockcount_99 = function() {
if (value <= stopValue) { // end count down. <= or >=
clearInterval(interval);
value = stopValue;
} else {
value = parseInt(value) - 1; // + 1 or - 1
localStorage.setItem("stockcount_99", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() {
stockcount_99();
}, speedcontrol);
With the following method can I isolate the two scripts and thus prevent any conflicts?
(function() {
...script 1...
})()
(function() {
...script 2...
})()

Tracking time and display it at next game

I have an assignment and I am a bit stuck. The assignment states:
Modify the game so that the time is tracked and a best time (or time to beat) is stored and displayed at the end of the game and at the beginning of the next game that is played. This functionality assumes the browser is not closed and that each successive game is begun through the "Play Again?" link. The display of the time to beat is shown below.
I have all files necessary, but I am stuck in this part. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var matchesFoundText;
var tileHeight = 30;
var tileWidth = 45;
var border = 1;
var globalPadding = 10;
var margin = 10;
var padding = 5;
var textTiles;
var flashcards = [
["a", "\u3042"],
["i", "\u3044"],
["u", "\u3046"],
["e", "\u3048"],
["o", "\u304A"],
["ka", "\u304B"],
["ki", "\u304D"],
["ku", "\u304F"],
["ke", "\u3051"],
["ko", "\u3053"],
["sa", "\u3055"],
["shi", "\u3057"],
["su", "\u3059"],
["se", "\u305B"],
["so", "\u305D"],
["ta", "\u305F"],
["chi", "\u3061"],
["tsu", "\u3064"],
["te", "\u3066"],
["to", "\u3068"],
["na", "\u306A"],
["ni", "\u306B"],
["nu", "\u306C"],
["ne", "\u306D"],
["no", "\u306E"],
["ha", "\u306F"],
["hi", "\u3072"],
["fu", "\u3075"],
["he", "\u3078"],
["ho", "\u307B"],
["ma", "\u307E"],
["mi", "\u307F"],
["mu", "\u3080"],
["me", "\u3081"],
["mo", "\u3082"],
["ya", "\u3084"],
["yu", "\u3086"],
["yo", "\u3088"],
["ra", "\u3089"],
["ri", "\u308A"],
["ru", "\u308B"],
["re", "\u308C"],
["ro", "\u308D"],
["wa", "\u308F"],
["wo", "\u3092"],
["n", "\u3093"]
];
function init() {
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
totalMatchesPossible = flashcards.length;
var numberOfTiles = totalMatchesPossible * 2;
matchesFound = 0;
var columns = 12;
timeAllowable = 500;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top";
txt.x = 700;
txt.y = 0;
stage.addChild(txt);
textTiles = [];
matchesFoundText = new Text(matchesFound + "/" + totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top";
matchesFoundText.x = 700;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
setPlacementArray(numberOfTiles);
for (var i = 0; i < numberOfTiles; i++) {
var placement = getRandomPlacement(placementArray);
var pairIndex = Math.floor(i / 2);
text = flashcards[pairIndex][i % 2];
var textTile = drawTextTile(text, pairIndex);
textTile.x = (tileWidth + margin) * (placement % columns) + globalPadding;
textTile.y = (tileHeight + margin) * Math.floor(placement / columns) + globalPadding;
stage.addChild(textTile);
background = new Shape();
background.x = textTile.x - padding;
background.y = textTile.y - padding;
background.graphics.setStrokeStyle(border).beginStroke("#000").beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
textTiles.push(background);
stage.addChildAt(background);
background.text = textTile;
background.onPress = handleOnPress;
stage.update();
};
}
function drawTextTile(text, pairIndex) {
textTile = new Text(text, "20px Monospace", "#000");
textTile.pairIndex = pairIndex;
textTile.textBaseline = "top";
return textTile;
}
function randomColor() {
var color = Math.floor(Math.random() * 255);
var color2 = Math.floor(Math.random() * 255);
var color3 = Math.floor(Math.random() * 255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles) {
for (var i = 0; i < numberOfTiles; i++) {
placementArray.push(i);
}
}
function getRandomPlacement(placementArray) {
randomNumber = Math.floor(Math.random() * placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event) {
var tile = event.target;
if (!!tileClicked === false || tileClicked === tile) {
tileClicked = tile;
} else {
tileClicked.graphics.beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
tile.graphics.beginFill('#aae').drawRect(0, 0, tileWidth, tileHeight);
if (tileClicked.text.pairIndex === tile.text.pairIndex && tileClicked.id != tile.id) {
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = matchesFound + "/" + totalMatchesPossible;
if (matchesFound === totalMatchesPossible) {
gameOver(true);
}
}
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
} else {
txt.text = secondsLeft + "... Game Over";
}
}
function replay() {
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
I give you 1 option for this, though you can do it also in other ways,
we declare global variables which are
var prev_time;
var best_time;
add that to your global variable declarations, then give it a value when you compute the time i guess we had that here:
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
//compute here the total time player had and give it to prev_time
//var totalTimePlayerplayed = some computation here which should be allowed time per player - secondsLeft
prev_time = totalTimePlayerplayed;
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play A
gain?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
if(best_time !== NULL){
best_time = prev_time;
//WE assume that the last player is the best scorer
}
} else {
//if there is already existing top scorer
if(best_time < prev_time){
best_time = prev_time
}
txt.text = secondsLeft + "... Game Over";
}
}
then give that time of the first player to the prev_time. Upon Game over or Game ended we validate here if the best_time has a value if not, then we give it a value of the value of prev_time, else we validate if the score is higher that the previous best_time and here's a tip, now when the player would trigger the "Play again" which I can't seem find right now, you get the variable best_time's value and display it as the score to beat. Hope you get the concept and somehow it helped you accomplished what you're intended to do, but like i said before you also have some other options to do this.

Javascript how to set interval time to stop scrolling

This is the demo in jsfiddle, demo
What I want is let the scrolled items('one ', 'two', 'three', '4', '5', '6', '7') automatically scroll up like the demo showed, and stop 2 sec when it's in the middle position. But in my demo, it will shack for a while after stopping in the middle position.
Here is the place in my demo code for setting position.
if ((x == 0) || (x % 35== 0)) {
setTimeout(function () {
i.top = x + 'px';
}, 1000);
} else {
i.top = x + 'px';
}
Any one can help me? Thanks!
UPDATE:
The reason why I set 35 is because I found that the scrolled items are approximately in the middle position when it equals to 0, -35,-70,-105,.... But when I console all x, I found that the value of x is between (31, -251). Do you know how to find the exact position when each items are in the middle of position? Thanks!
i modified your code a bit,
i set a variable "k" that the interval is assigned to and i clear the interval on stop and start it again after the timeout
looks good for me -> http://jsfiddle.net/ato0mf7u/3/
no funny shakin anymore ;-D
window.onload = addScrollers;
var i = 1;
var arr = ['one ', 'two', 'three', '4', '5', '6', '7'];
var mid;
var k;
function addScrollers() {
var txt = arr[0];
while (i < arr.length) {
txt += '<p>' + arr[i] + '</p>';
i++;
}
startScroll('myscroller', txt);
}
var speed = 10; // scroll speed (bigger = faster)
var dR = false; // reverse direction
var step = 1;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
function objHeight(obj) {
if (obj.offsetHeight) return obj.offsetHeight;
if (obj.clip) return obj.clip.height;
return 0;
}
function scrF(i, sH, eH) {
var x = parseInt(i.top) + (dR ? step : -step);
if (dR && x > sH) {
x = -eH;
} else if (x < 1 - eH) {
x = sH;
}
//when x is the times of 35, the positio is in middle
if ((x == 0) || (x % 35== 0)) {
clearInterval(k);
setTimeout(function () {
i.top = x + 'px';
k = setInterval(function () {
scrF(i, sH, eH);
}, 1000 / speed);
}, 1000);
}
else {
i.top = x + 'px';
}
return x;
}
function startScroll(sN, txt) {
var scr = document.getElementById(sN);
var sW = objWidth(scr);
var sH = objHeight(scr);
scr.innerHTML = '<div id="' + sN + 'in" style="position:absolute; left:3px; width:' + sW + ';">' + txt + '<\/div>';
var sTxt = document.getElementById(sN + 'in');
var eH = objHeight(sTxt);
mid = (eH - sH) / 2;
sTxt.style.top = (dR ? -eH : sH) + 'px';
sTxt.style.clip = 'rect(0,' + sW + 'px,' + eH + 'px,0)';
k = setInterval(function () {
scrF(sTxt.style, sH, eH);
}, 1000 / speed);
}

jQuery How to Have Variable Increment by Value in a Recursive Function

I have a JS Function which is called in document.ready. The intent is as it scrolls to the bottom window, it'll load more from the JSON API.
The API has the parameter offset and limit. Offset controls which subset of results you are seeing. For ex. 20-40 would be offset=20 and limit controls how many you can view at once.
I thought I would approach this with a recursive function which calls itself each time the user goes to the bottom of the window, with window.scroll. Once they go to the bottom, it'll increment the offset by 20 each time, then run the function again.
Problem: I can't seem to get it to increment the variable by 20 to make this work. Thoughts?
function getData(offset) {
var jsonCallback = "&jsoncallback=?";
//var offset = 20;
//var offset += 20;
var limit = 20;
var characterURL = "http://api.example.com/character&byId=" + characterID + "&offset=" + offset + "&limit=" + limit;
$.getJSON(characterURL + jsonCallback, function(data) {
for (i=0; i < (data.data.results).length; i++) {
var $characterUl = $("<ul>");
$characterUl.appendTo("#characterComics");
$("<li>").text(data.data.results[i].title).appendTo($characterUl);
$("<li>").text(data.data.results[i].id).appendTo($characterUl);
$("<li>").text(data.data.results[i].release_date).appendTo($characterUl);
if (data.data.results[i].release_date > 0) {
$characterLi.text(data.data.results[i].issue_number).appendTo($characterUl);
}
}
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 10) {
while ((data.data.results).length === offset || (data.data.results).length > offset) {
offset = offset+20;
$("<div>").text(offset).appendTo("body");
getComics(offset);
}
}
});
});
}
$(document).ready(function() {
var $characterComics = $("<div>", {id : "characterComics"});
$characterComics.appendTo("body");
getData(0);
});
UPDATED
Read this more as a pseudo-code
function getData(offset) {
var jsonCallback = "&jsoncallback=?",
characterURL = "http://api.example.com/character&byId=" + characterID + "&offset=" + offset + "&limit=" + limit;
$.getJSON(characterURL + jsonCallback, function(data) {
for (i=0; i < (data.data.results).length; i++) {
var $listItem = $("<li>");
listItem.append("<span>"+data.data.results[i].title+"</span>");
listItem.append("<span>"+data.data.results[i].id+"</span>");
listItem.append("<span>"+data.data.results[i].release_date+"</span>");
if (data.data.results[i].release_date > 0) {
listItem.append("<span>"+data.data.results[i].issue_number+"</span>");
}
listItem.appendTo($characterUl);
itemsLoaded++;
}
});
}
$(document).ready(function() {
var $characterComics = $("<div>", {id : "characterComics"}),
$characterUl = $("<ul>"),
offset = 0,
itemsLoaded = 0;
limit = 20;
$characterComics.appendTo("body");
$characterUl.appendTo($characterComics);
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 10) {
if ("check here if you reached your offsets") {
offset = offset+20;
getData(offset);
}
}
});
// get your first set of data
getData(0);
});

Coinslider...adding code to stop looping

I'm using the Coin Slider on my website but encountered a very unexpected surprise today when my client asked me to have the slideshow stop on the last slide. Apparently it's not built in and there's no option to have it stop.
I was hoping someone could help me find where it's looping in the script and suggest a way to add in this option.
I don't even mind having 2 versions of the script, one that loops and one that doesn't.
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load("http://localhost/auxtest/"+sourceURL+"");
}
(function($) {
var params = new Array;
var order = new Array;
var images = new Array;
var links = new Array;
var linksTarget = new Array;
var titles = new Array;
var interval = new Array;
var imagePos = new Array;
var appInterval = new Array;
var squarePos = new Array;
var reverse = new Array;
$.fn.coinslider= $.fn.CoinSlider = function(options){
init = function(el){
order[el.id] = new Array(); // order of square appereance
images[el.id] = new Array();
links[el.id] = new Array();
linksTarget[el.id] = new Array();
titles[el.id] = new Array();
imagePos[el.id] = 0;
squarePos[el.id] = 0;
reverse[el.id] = 1;
params[el.id] = $.extend({}, $.fn.coinslider.defaults, options);
// create images, links and titles arrays
$.each($('#'+el.id+' img'), function(i,item){
images[el.id][i] = $(item).attr('src');
links[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('href') : '';
linksTarget[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('target') : '';
titles[el.id][i] = $(item).next().is('span') ? $(item).next().html() : '';
$(item).hide();
$(item).next().hide();
});
// set panel
$(el).css({
'background-image':'url('+images[el.id][0]+')',
'width': params[el.id].width,
'height': params[el.id].height,
'position': 'relative',
'background-position': 'top left'
}).wrap("<div class='coin-slider' id='coin-slider-"+el.id+"' />");
// create title bar
$('#'+el.id).append("<div class='cs-title' id='cs-title-"+el.id+"' style='position:absolute; bottom:0; left:0; z-index: 1000;'></div>");
$.setFields(el);
if(params[el.id].navigation)
$.setNavigation(el);
$.transition(el,0);
$.transitionCall(el);
}
// squares positions
$.setFields = function(el){
tWidth = sWidth = parseInt(params[el.id].width/params[el.id].spw);
tHeight = sHeight = parseInt(params[el.id].height/params[el.id].sph);
counter = sLeft = sTop = 0;
tgapx = gapx = params[el.id].width - params[el.id].spw*sWidth;
tgapy = gapy = params[el.id].height - params[el.id].sph*sHeight;
for(i=1;i <= params[el.id].sph;i++){
gapx = tgapx;
if(gapy > 0){
gapy--;
sHeight = tHeight+1;
} else {
sHeight = tHeight;
}
for(j=1; j <= params[el.id].spw; j++){
if(gapx > 0){
gapx--;
sWidth = tWidth+1;
} else {
sWidth = tWidth;
}
order[el.id][counter] = i+''+j;
counter++;
if(params[el.id].links)
$('#'+el.id).append("<a href='"+links[el.id][0]+"' class='cs-"+el.id+"' id='cs-"+el.id+i+j+"' style='width:"+sWidth+"px; height:"+sHeight+"px; float: left; position: absolute;'></a>");
else
$('#'+el.id).append("<div class='cs-"+el.id+"' id='cs-"+el.id+i+j+"' style='width:"+sWidth+"px; height:"+sHeight+"px; float: left; position: absolute;'></div>");
// positioning squares
$("#cs-"+el.id+i+j).css({
'background-position': -sLeft +'px '+(-sTop+'px'),
'left' : sLeft ,
'top': sTop
});
sLeft += sWidth;
}
sTop += sHeight;
sLeft = 0;
}
$('.cs-'+el.id).mouseover(function(){
$('#cs-navigation-'+el.id).show();
});
$('.cs-'+el.id).mouseout(function(){
$('#cs-navigation-'+el.id).hide();
});
$('#cs-title-'+el.id).mouseover(function(){
$('#cs-navigation-'+el.id).show();
});
$('#cs-title-'+el.id).mouseout(function(){
$('#cs-navigation-'+el.id).hide();
});
if(params[el.id].hoverPause){
$('.cs-'+el.id).mouseover(function(){
params[el.id].pause = true;
});
$('.cs-'+el.id).mouseout(function(){
params[el.id].pause = false;
});
$('#cs-title-'+el.id).mouseover(function(){
params[el.id].pause = true;
});
$('#cs-title-'+el.id).mouseout(function(){
params[el.id].pause = false;
});
}
};
$.transitionCall = function(el){
clearInterval(interval[el.id]);
delay = params[el.id].delay + params[el.id].spw*params[el.id].sph*params[el.id].sDelay;
interval[el.id] = setInterval(function() { $.transition(el) }, delay);
}
// transitions
$.transition = function(el,direction){
if(params[el.id].pause == true) return;
$.effect(el);
squarePos[el.id] = 0;
appInterval[el.id] = setInterval(function() { $.appereance(el,order[el.id][squarePos[el.id]]) },params[el.id].sDelay);
$(el).css({ 'background-image': 'url('+images[el.id][imagePos[el.id]]+')' });
if(typeof(direction) == "undefined")
imagePos[el.id]++;
else
if(direction == 'prev')
imagePos[el.id]--;
else
imagePos[el.id] = direction;
if (imagePos[el.id] == images[el.id].length) {
imagePos[el.id] = 0;
}
if (imagePos[el.id] == -1){
imagePos[el.id] = images[el.id].length-1;
}
$('.cs-button-'+el.id).removeClass('cs-active');
$('#cs-button-'+el.id+"-"+(imagePos[el.id]+1)).addClass('cs-active');
if(titles[el.id][imagePos[el.id]]){
$('#cs-title-'+el.id).css({ 'opacity' : 0 }).animate({ 'opacity' : params[el.id].opacity }, params[el.id].titleSpeed);
$('#cs-title-'+el.id).html(titles[el.id][imagePos[el.id]]);
} else {
$('#cs-title-'+el.id).css('opacity',0);
}
};
$.appereance = function(el,sid){
$('.cs-'+el.id).attr('href',links[el.id][imagePos[el.id]]).attr('target',linksTarget[el.id][imagePos[el.id]]);
if (squarePos[el.id] == params[el.id].spw*params[el.id].sph) {
clearInterval(appInterval[el.id]);
return;
}
$('#cs-'+el.id+sid).css({ opacity: 0, 'background-image': 'url('+images[el.id][imagePos[el.id]]+')' });
$('#cs-'+el.id+sid).animate({ opacity: 1 }, 300);
squarePos[el.id]++;
};
// navigation
$.setNavigation = function(el){
// create prev and next
$(el).append("<div id='cs-navigation-"+el.id+"'></div>");
$('#cs-navigation-'+el.id).hide();
$('#cs-navigation-'+el.id).append("<a href='#' id='cs-prev-"+el.id+"' class='cs-prev'> </a>");
$('#cs-navigation-'+el.id).append("<a href='#' id='cs-next-"+el.id+"' class='cs-next'> </a>");
$('#cs-navigation-'+el.id).append("<a href='javascript:loadContent('#world', 'auxworld.php');' id='cs-back-"+el.id+"' class='cs-back'> </a>");
$('#cs-prev-'+el.id).css({
'position' : 'absolute',
'top' : params[el.id].height/2 - 15,
'left' : 0,
'z-index' : 1001,
'line-height': '30px',
'opacity' : params[el.id].opacity
}).click( function(e){
e.preventDefault();
$.transition(el,'prev');
$.transitionCall(el);
}).mouseover( function(){ $('#cs-navigation-'+el.id).show() });
$('#cs-next-'+el.id).css({
'position' : 'absolute',
'top' : params[el.id].height/2 - 15,
'right' : 0,
'z-index' : 1005,
'line-height': '30px',
'opacity' : params[el.id].opacity
}).click( function(e){
e.preventDefault();
$.transition(el);
$.transitionCall(el);
}).mouseover( function(){ $('#cs-navigation-'+el.id).show() });
$('#cs-back-'+el.id).css({
'position' : 'absolute',
'top' : params[el.id].height/2 - 15,
'right' : 0,
'z-index' : 1001,
'line-height': '30px',
'opacity' : params[el.id].opacity
}).click( function(){
window.location.replace('index.php');
// loadContent('#world', 'auxworld.php');
}).mouseover( function(){ $('#cs-navigation-'+el.id).show() });
// image buttons
$("<div id='cs-buttons-"+el.id+"' class='cs-buttons'></div>").appendTo($('#coin-slider-'+el.id));
for(k=1;k<images[el.id].length+1;k++){
$('#cs-buttons-'+el.id).append("<a href='#' class='cs-button-"+el.id+"' id='cs-button-"+el.id+"-"+k+"'>"+k+"</a>");
}
$.each($('.cs-button-'+el.id), function(i,item){
$(item).click( function(e){
$('.cs-button-'+el.id).removeClass('cs-active');
$(this).addClass('cs-active');
e.preventDefault();
$.transition(el,i);
$.transitionCall(el);
})
});
$('#cs-navigation-'+el.id+' a').mouseout(function(){
$('#cs-navigation-'+el.id).hide();
params[el.id].pause = false;
});
$("#cs-buttons-"+el.id).css({
'left' : '50%',
'margin-left' : -images[el.id].length*15/2-5,
'position' : 'relative'
});
}
// effects
$.effect = function(el){
effA = ['random','swirl','rain','straight'];
if(params[el.id].effect == '')
eff = effA[Math.floor(Math.random()*(effA.length))];
else
eff = params[el.id].effect;
order[el.id] = new Array();
if(eff == 'random'){
counter = 0;
for(i=1;i <= params[el.id].sph;i++){
for(j=1; j <= params[el.id].spw; j++){
order[el.id][counter] = i+''+j;
counter++;
}
}
$.random(order[el.id]);
}
if(eff == 'rain') {
$.rain(el);
}
if(eff == 'swirl')
$.swirl(el);
if(eff == 'straight')
$.straight(el);
reverse[el.id] *= -1;
if(reverse[el.id] > 0){
order[el.id].reverse();
}
}
// shuffle array function
$.random = function(arr) {
var i = arr.length;
if ( i == 0 ) return false;
while ( --i ) {
var j = Math.floor( Math.random() * ( i + 1 ) );
var tempi = arr[i];
var tempj = arr[j];
arr[i] = tempj;
arr[j] = tempi;
}
}
//swirl effect by milos popovic
$.swirl = function(el){
var n = params[el.id].sph;
var m = params[el.id].spw;
var x = 1;
var y = 1;
var going = 0;
var num = 0;
var c = 0;
var dowhile = true;
while(dowhile) {
num = (going==0 || going==2) ? m : n;
for (i=1;i<=num;i++){
order[el.id][c] = x+''+y;
c++;
if(i!=num){
switch(going){
case 0 : y++; break;
case 1 : x++; break;
case 2 : y--; break;
case 3 : x--; break;
}
}
}
going = (going+1)%4;
switch(going){
case 0 : m--; y++; break;
case 1 : n--; x++; break;
case 2 : m--; y--; break;
case 3 : n--; x--; break;
}
check = $.max(n,m) - $.min(n,m);
if(m<=check && n<=check)
dowhile = false;
}
}
// rain effect
$.rain = function(el){
var n = params[el.id].sph;
var m = params[el.id].spw;
var c = 0;
var to = to2 = from = 1;
var dowhile = true;
while(dowhile){
for(i=from;i<=to;i++){
order[el.id][c] = i+''+parseInt(to2-i+1);
c++;
}
to2++;
if(to < n && to2 < m && n<m){
to++;
}
if(to < n && n>=m){
to++;
}
if(to2 > m){
from++;
}
if(from > to) dowhile= false;
}
}
// straight effect
$.straight = function(el){
counter = 0;
for(i=1;i <= params[el.id].sph;i++){
for(j=1; j <= params[el.id].spw; j++){
order[el.id][counter] = i+''+j;
counter++;
}
}
}
$.min = function(n,m){
if (n>m) return m;
else return n;
}
$.max = function(n,m){
if (n<m) return m;
else return n;
}
this.each (
function(){ init(this); }
);
};
// default values
$.fn.coinslider.defaults = {
width: 1230, // width of slider panel
height: 500, // height of slider panel
spw: 20, // squares per width
sph: 1, // squares per height
delay: 7000, // delay between images in ms
sDelay: .1, // delay beetwen squares in ms
opacity: 0.9, // opacity of title and navigation
titleSpeed: 1160, // speed of title appereance in ms
effect: 'rain', // random, swirl, rain, straight
navigation: true, // prev next and buttons
links : false, // show images as links
hoverPause: true // pause on hover
};
})(jQuery);
I've updated the code of coin slider with extra option stopAtLastSlide, that can be passed to coinslider function stop the automatic rotation when it reaches last image.
Check working example here http://jsfiddle.net/wtk_pl/Lrsj2/7/. Source code for updated coin slider can be found here https://github.com/WTK/Coin-Slider.
I would try to modify the $.transitionCall function. This set's the new timeout for displaying the next element.
Maybe you can find out here if it wants to render the last element and then skip setting the interval
$.transitionCall = function(el) {
clearInterval(interval[el.id]);
delay = params[el.id].delay + params[el.id].spw * params[el.id].sph * params[el.id].sDelay;
interval[el.id] = setInterval(function() {
$.transition(el)
}, delay);
}
Another option for not stopping the interval is setting params[el.id].pause = true;

Categories