I use the below fixedtableheader plugin on a golf leaderboard page that uses AJAX and setInterval to fetch score changes from the server. Without the plugin everything works well, with the plugin, there is a constant memory leak that during the course of the day make Firefox go from 60MB at start to 1.5GB before end of day and crash. Can anyone spot any memory leaks in this code?
The page in question is http://scoring.pgalinks.net/leaderboards/lobby.cfm?from=so
jQuery.fn.fixedtableheader = function (options) {
var settings = jQuery.extend({
headerrowsize: 1,
highlightrow: false,
highlightclass: "highlight"
}, options);
this.each(function (i) {
var $tbl = $(this);
var $tblhfixed = $tbl.find("tr:lt(" + settings.headerrowsize + ")");
var headerelement = "th";
if ($tblhfixed.find(headerelement).length == 0) headerelement = "td";
if ($tblhfixed.find(headerelement).length > 0) {
$tblhfixed.find(headerelement).each(function () {
$(this).css("width", $(this).width());
});
var $clonedTable = $tbl.clone().empty();
var tblwidth = GetTblWidth($tbl);
$clonedTable.attr("id", "fixedtableheader" + i).css({
"position": "fixed",
"top": "0",
"left": $tbl.offset().left
}).append($tblhfixed.clone()).width(tblwidth).hide().appendTo($("body"));
if (settings.highlightrow) $("tr:gt(" + (settings.headerrowsize - 1) + ")", $tbl).hover(function () {
$(this).addClass(settings.highlightclass);
}, function () {
$(this).removeClass(settings.highlightclass);
});
$(window).scroll(function () {
if (jQuery.browser.msie && jQuery.browser.version == "6.0") $clonedTable.css({
"position": "absolute",
"top": $(window).scrollTop(),
"left": $tbl.offset().left
});
else $clonedTable.css({
"position": "fixed",
"top": "0",
"left": $tbl.offset().left - $(window).scrollLeft()
});
var sctop = $(window).scrollTop();
var elmtop = $tblhfixed.offset().top;
if (sctop > elmtop && sctop <= (elmtop + $tbl.height() - $tblhfixed.height())) $clonedTable.show();
else $clonedTable.hide();
});
$(window).resize(function () {
if ($clonedTable.outerWidth() != $tbl.outerWidth()) {
$tblhfixed.find(headerelement).each(function (index) {
var w = $(this).width();
$(this).css("width", w);
$clonedTable.find(headerelement).eq(index).css("width", w);
});
$clonedTable.width($tbl.outerWidth());
}
$clonedTable.css("left", $tbl.offset().left);
});
}
});
function GetTblWidth($tbl) {
var tblwidth = $tbl.outerWidth();
return tblwidth;
}
};
Related
everyone! Searching the internet for solutions related to stick a widget in the sidebar I've found one that I liked. But, the only problem is that it doesn't "break" before the footer. I've already tried a lot of solutions, but without sucess until now. If someone can help me, I thank!
This is the original script:
<script type='text/javascript'>
/*<![CDATA[*/
// Sticky Plugin
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Created: 2/14/2011
// Date: 9/12/2011
// Website: http://labs.anthonygarand.com/sticky
// Description: Makes an element on the page stick on the screen as you scroll
// For Blogger by : http://www.makingdifferent.com
(function($) {
var defaults = {
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
center: false
},
$window = $(window),
$document = $(document),
sticked = [],
windowHeight = $window.height(),
scroller = function() {
var scrollTop = $window.scrollTop(),
documentHeight = $document.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
for (var i = 0; i < sticked.length; i++) {
var s = sticked[i],
elementTop = s.stickyWrapper.offset().top,
etse = elementTop - s.topSpacing - extra;
if (scrollTop <= etse) {
if (s.currentTop !== null) {
s.stickyElement.css('position', '').css('top', '').removeClass(s.className);
s.currentTop = null;
}
}
else {
var newTop = documentHeight - s.elementHeight - s.topSpacing - s.bottomSpacing - scrollTop - extra;
if (newTop < 0) {
newTop = newTop + s.topSpacing;
} else {
newTop = s.topSpacing;
}
if (s.currentTop != newTop) {
s.stickyElement.css('position', 'fixed').css('top', newTop).addClass(s.className);
s.currentTop = newTop;
}
}
}
},
resizer = function() {
windowHeight = $window.height();
};
// should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
if (window.addEventListener) {
window.addEventListener('scroll', scroller, false);
window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', scroller);
window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(options) {
var o = $.extend(defaults, options);
return this.each(function() {
var stickyElement = $(this);
if (o.center)
var centerElement = "margin-left:auto;margin-right:auto;";
stickyId = stickyElement.attr('id');
stickyElement
.wrapAll('<div id="' + stickyId + 'StickyWrapper" style="' + centerElement + '"></div>')
.css('width', stickyElement.width());
var elementHeight = stickyElement.outerHeight(),
stickyWrapper = stickyElement.parent();
stickyWrapper
.css('width', stickyElement.outerWidth())
.css('height', elementHeight)
.css('clear', stickyElement.css('clear'));
sticked.push({
topSpacing: o.topSpacing,
bottomSpacing: o.bottomSpacing,
stickyElement: stickyElement,
currentTop: null,
stickyWrapper: stickyWrapper,
elementHeight: elementHeight,
className: o.className
});
});
};
})(jQuery);
/*]]>*/
</script>
I have been reading several similar questions about this, but I can't get it to work. I have a scroll detection function in jQuery, which I want to have 3 parameters:
function scroll_detection(box_selector, trigger_offset, the_animation){
//something here
the_animation();
}
Where the_animation is a function that will be called like this:
scroll_detection("section", .8, function(){
//stuff here
});
The problem is, when I add the function, the animation do not run anymore.
This code works perfectly:
function scroll_detection(duration, box_selector, element_selector, ease, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
$(this).find(element_selector).animate( { marginLeft: "0" }, duration, ease );
}
});
});
}
scroll_detection(2000, "section", ".section-title", "easeOutBack", .8);
scroll_detection(3000, ".article-wrap", ".article-title", "easeOutBounce", .7);
But this does not:
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation();
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
I want to be able to change easily what kind of effect I want. Any help will be appreciated.
Edit 11/09/2015:
As #Aguardientico and #LuiGui pointed out, the problem was the scope of the $(this) inside the callback function, and I went with the #Aguardientico solution.
jQuery(document).ready(function($){
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation.call(post); //Add call to give the function the right scope
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
It looks like an issue related with scope, you are calling $(this) inside your anonymous function aka the_animation, what if you do the following? the_animation.call(post)
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation.call(post);
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
You are function calls DO NOT match the function definitions.
Your parameters are OUT OF ORDER.
Try this NEW CODE:
var scroll_detection = function scroll_detection_func(
the_animation, box_selector, trigger_offset
){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top
- ($(window).scrollTop()
+ effect_offset)
;
if (position <= 0) {
the_animation();
}
});
});
}
scroll_detection(
function(){
$(this).find(".section-title").animate({
marginLeft: "0" },
2000, "easeOutBounce"
);
}, //the_animation
"section", //box_selector
.8 //trigger_offset
);
From the code you give,the_animation means
$(this).find(element_selector).animate( { marginLeft: "0" }, duration, ease );
so you can there is a this in your function. When you pass a function with this as a parameter, you need to specify what this mean, just try to specify the scope of this use apply(),bind() or 'call()' function, here are some explanations:
http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
I would like to replicate the same functionality as at ign.com, where the indicator bar fills up over time. I got it working but I got some sync issues after a while. So i'm open to suggestions to do it from scratch (I'm beginner with all this animation stuff).
This is the code.
function GoProgressBar() {
var $lineStatus = $('.featured-articles-line-status');
$lineStatus.css('width', '0px');
$lineStatus.animate({ width: '694px' }, 12000, 'linear', GoProgressBar);
};
function GoOverlay(width, isLast, currentWidth) {
var $overlayLine = $('.status-overlay');
if (isLast) {
$overlayLine.css('width', '0px');
return;
}
if (currentWidth) {
$overlayLine.css('width', currentWidth);
$overlayLine.animate({ width: width }, 700);
} else {
$overlayLine.css('width', '0px');
$overlayLine.animate({ width: width }, 700);
}
};
function ShowNextElement() {
var $elements = $('.element'),
$overlayLine = $('.status-overlay'),
$liElements = $('#elements li'),
width;
if (currentElement === elements[elements.length - 1]) {
currentWidth = $overlayLine.width() + 'px',
width = currentWidth + $($liElements[(elements.length - 1)]).outerWidth() + 'px';
GoOverlay(width, true, currentWidth);
currentElement = elements[0];
$elements.hide();
$(currentElement).fadeIn(1000);
return;
}
i = elements.indexOf(currentElement) + 1;
var currentTab = $liElements[(i - 1)],
currentWidth = $overlayLine.width();
if (currentWidth) {
width = currentWidth + $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, currentWidth);
} else {
width = $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, false);
}
currentElement = elements[i];
$elements.hide();
$(currentElement).fadeIn(1000);
}
Thanks!
http://jqueryui.com/progressbar/
You could try this..
There are more features in addition to this,check it out.
Might come useful :)
There are a wealth of ways in which you could do this.
You should have some kind of controller to manage the show and hide.
var Application = {
show : function() {
jQuery('.application-overlay').stop().animate({ top: 40 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 1000},500);
},
hide : function() {
jQuery('.application-overlay').stop().animate({ top: -1200 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 200},500);
}
};
Then you have your triggers : Application.show();
jQuery(document).ready(function() {
jQuery('.cf-speakers .span2 a').hover(function() {
jQuery('span',this).stop().animate({ opacity: 1.0 },100);
}, function() {
jQuery('span',this).stop().animate({ opacity: 0.0 },100);
});;
jQuery('.apply-now').click(function(e) {
Application.show();
e.stopPropagation();
e.preventDefault();
});
jQuery('body').click(function(e) {
var application = jQuery('.application-overlay');
if( application.has(e.target).length === 0)
Application.hide();
});
jQuery('.gallery a').click(function(e) {
var src = jQuery(this).attr('href');
jQuery('.main-container img').hide().attr('src', src).fadeIn('fast');
jQuery('.gallery a').each(function() {
jQuery(this).removeClass('active');
});
jQuery(this).addClass('active');
e.stopPropagation();
e.preventDefault();
});
});
Your css would of course come into play also but that can be left to you!
This should give you an example of what you need .. But you're already on the right track, sometimes there is merit in reusing other people code too you know! :)
In our site www.mydubaitrip.com I have a script that resizes the background image base on the browser width. My problem is whenever I try to press Ctrl+F5 or if I navigate to hotel page and back to home page, the background image doesn't resize correctly and my layout looks messed up. But if I try to press F5 again it will now adjust accordingly. I cannot figure out what is the problem.
Here's the script that I used.
var minWidth = 1024;
var minHeight = 844;
var winRatio = new Array();
var imgReady = new Array();
var orientation = 90;
var debounceId;
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (isiPad) {
var minWidth = 980;
}
var readyToRotate = false;
var readyToResize = true;
var miniContentWrapperHeight = 444;
// BACKGROUND TRANSITION
var theTimer;
var currBanner = -1;
var totalBanner = 0;
var timeWaiting = parseInt(500);
var timeTextTransIn = parseInt(1000);
var timeTextTransOut = parseInt(1000);
var timeTransCross = parseInt(2000);
var timeTransInit = parseInt(0);
var timeTransInterval = parseInt(7000);
var transitioning = false;
$("#homePageMainPanel").css({ "backgroundColor": "black" });
var hybridMode = true;
if (($.browser.mozilla && $.browser.version == "5.0") ||
$.browser.msie && $.browser.version == "9.0") {
//hybridMode = false;
}
//$("html").css({ "overflow": "hidden" });
function updateOrientation() {
// scroll and hide address bar for iPhone landscape
setTimeout(function() { window.scrollTo(0, 1) }, timeWaiting);
if (window.orientation != undefined)
orientation = Math.abs(window.orientation);
resizeBackground();
}
$(window).load(function() {
resizeBackground();
if (!($.browser.msie && $.browser.version == "6.0")) {
var lang = $('meta[name="language"]').attr("content");
if ((lang == "ar") || (lang == "ir")) {
$(".carouselShadow").css('background', 'url(/media/images/fg_ar_text_bg.png) no-repeat');
}
else {
$(".carouselShadow").css('background', 'url(/media/images/fg_text_bg.png) no-repeat');
}
}
});
$(document).ready(function() {
if (typeof BackgroundInfo != 'undefined' && BackgroundInfo.length > 0) {
$("#carousel").append("<img src=\"" + BackgroundInfo[0].Src + "\" alt=\"" + BackgroundInfo[0].Alt + "\" />");
}
if ($(window).height() > $(document).height() - $("#bottomLayer").height()) {
$("#bottomLayer").css({ 'position': 'absolute', "top": parseInt($(window).height() - $("#bottomLayer").height()) });
$("#carousel img").height($(window).height() - $("#bottomLayer").height());
//alert($("#bottomLayer").offset().bottom);
$(".bookPanel").css({ 'position': 'relative', "bottom": parseInt($(".bookPanel").height() - $("#carousel").height() + 28) });
$(".carouselShadow").css({ 'position': 'relative', "bottom": parseInt($(".carouselShadow").height() - $("#carousel").height()+20) });
setTimeout(function() {
$("#bottomLayer").css({ "position": "relative", "top": parseInt($(window).height() - $("#bottomLayer").height()) });
}, 500);
setTimeout(function() {
$(".bookPanel").css({ "position": "relative", "bottom": parseInt($(".bookPanel").height() - $("#carousel").height() + 28) });
}, 500);
setTimeout(function() {
$(".carouselShadow").css({ "position": "relative", "bottom": parseInt($(".carouselShadow").height() - $("#carousel").height()+20) });
}, 500);
}
//in case the navigation height is longer than prefixed minheight, adjust minheight=navigation height
var homepageHeight = $("#homePageMainPanel").height() + $("#bottomLayer").height();
if (homepageHeight > minHeight)
minHeight = homepageHeight;
//this is only for mobile safari on ipad/iphone
window.onorientationchange = function() {
window.scrollTo(0, 1); // to prevent jumpy and blinky page transitions
updateOrientation();
}
$(window)
.resize(function() {
if (readyToResize) {
clearTimeout(debounceId);
debounceId = setTimeout(resizeEvent, 500);
}
})
.load(function() {
// scroll and hide address bar for iPhone landscape
setTimeout(function() { window.scrollTo(0, 1) }, timeWaiting);
});
initRotateBanner();
});
var winWidth = $(window).width();
var winHeight = $(window).height();
var winNewWidth = -1;
var winNewHeight = -1;
function resizeEvent() {
// JL: Hack to prevent IE 7,8 to have infinite loop when window.resize event
winNewWidth = $(window).width();
winNewHeight = $(window).height();
if (winWidth != winNewWidth || winHeight != winNewHeight) {
clearTimeout(debounceId);
resizeBackground();
}
winWidth = winNewWidth;
winHeight = winNewHeight;
}
function initRotateBanner() {
$('#carousel img').eq(0).one('load', function() {
if (readyToRotate = true) {
if (typeof BackgroundInfo != 'undefined' && BackgroundInfo.length > 0) {
$.each(BackgroundInfo, function(i, v) {
if (i > 0) {
$("#carousel").append("<img src=\"" + BackgroundInfo[i].Src + "\" alt=\"" + BackgroundInfo[i].Alt + "\" />");
}
});
initBackgroundImageReady();
}
imgReady[0] = true;
window.setTimeout("rotateBanner('init')", timeTransInit);
}
//$('#background').children("img").show();
//$('#background').children("img").css({ 'opacity': '1' });
resizeBackground();
}).each(function() {
// $(this).load();
});
/// assign each background text accordingly
var index = 0;
$('.carouselContentContainer').each(function() {
$(this).attr('id', 'text_box_' + index);
index++;
});
}
function initBackgroundImageReady() {
$('#carousel').children("img").each(function() {
//assign each background id accordingly
$(this).attr('id', 'img_box_' + totalBanner);
// flag correspondingly when bg images is loaded
imgReady[totalBanner] = false;
$(this).one('load', function(event) {
var id = $(this).attr('id');
var idArr = new Array();
idArr = id.split('_');
var index = idArr[idArr.length - 1];
//console.log(index + "loaded");
imgReady[index] = true;
resizeBackground();
});
//$(this).load();
totalBanner++;
});
}
function resizeBackground() {
readyToResize = false;
$('html').css({ 'overflow': 'hidden' });
$("#carousel").children("img").each(function() {
var oriWidth = $(this).width('');
var oriHeight = $(this).height('');
var bgWidth = $(window).width();
if (bgWidth < minWidth)
bgWidth = minWidth;
var bgHeight = bgWidth / oriWidth * oriHeight;
if (oriHeight < bgWrapperHeight)
bgWrapperHeight = oriHeight;
$(this).css({ 'position': 'absolute', 'width': bgWidth, 'height': bgHeight });
});
//start with window height & width
var bgWrapperHeight = $(window).height();
var bgWrapperWidth = $(window).width();
// if vertical scrollbar exists, accommodate the scrollbar width (16px)
if ($.browser.webkit == true) {
////$("#log").prepend(document.body.scrollHeight + " : " + document.body.clientHeight + "<br />");
if (document.body.scrollHeight < document.body.clientHeight)
bgWrapperWidth = $(window).width() - 16; // accomdate the scroll bar width (16px)
else
bgWrapperWidth = $(window).width();
}
else {
////$("#log").prepend($(document).height() + " : " + $(window).height() + "<br />");
if ($(window).height() < $(document).height())
bgWrapperWidth = $(window).width() - 17; //
else
bgWrapperWidth = $(window).width();
}
// for screen size > min height (hp-navigation) but < min background image size, adjust to fit without scroller
if (bgWrapperHeight + $('#bottomLayer').height() > $(window).height()) {
bgWrapperHeight = $(window).height() - $('#bottomLayer').height();
}
//wrapper height should not go lower than navigation height
if (bgWrapperHeight < $('#bookPanel').height())
bgWrapperHeight = $('#bookPanel').height();
//wrapper width should not go lower than min width
if (bgWrapperWidth < minWidth)
bgWrapperWidth = minWidth;
// set #hp-content-wrapper height
$('#homePageMainPanel').css({ 'height': bgWrapperHeight, 'width': bgWrapperWidth });
$('#carousel').css({ 'height': bgWrapperHeight, 'width': bgWrapperWidth });
$('#bottomLayer').css({ 'width': bgWrapperWidth });
$('html').css({ 'overflow': 'auto' });
//TODO: better way to center align bg image!
//var nn = 0;
// vertically middle align background
$("#carousel").children("img").each(function() {
// IF document height (minus footer height) is more than background image,
// Expand Background Image Vertically!
if (($(document).height() - $('#bottomLayer').height()) >= $(this).height()) {
var newHeight = $(document).height() - $('#bottomLayer').height();
var newWidth = Math.round((newHeight / $(this).height()) * $(this).width());
var offsetX = ((bgWrapperWidth - newWidth) / 2);
$(this).css({ 'position': 'absolute', 'left': offsetX, 'width': newWidth, 'height': newHeight });
// $("#log").prepend($(document).height() + " : " + $('#footer').height() + "<br />");
// Reset back the image top position to 0;
$(this).css({ 'position': 'absolute', 'top': 0 });
}
else { //TODO: figure out what contributes to offset??
var newWidth = $(document).width();
var newHeight = Math.round((newWidth / $(this).width()) * $(this).height());
var offsetX = ((bgWrapperWidth - newWidth) / 2);
// Reset back the image left position to 0;
$(this).css({ 'position': 'absolute', 'left': 0, 'width': newWidth, 'height': newHeight });
// $(this).css({ 'position': 'absolute', 'left': 0, 'width': '100%', 'height': '' });
if (bgWrapperHeight > $('#bottomLayer').position().top) {
var offsetY = ((bgWrapperHeight - $(this).height()) / 2);
$(this).css({ 'top': offsetY });
}
else {
var offsetY = (($('#bottomLayer').position().top - $(this).height()) / 2);
$(this).css({ 'top': offsetY });
}
}
});
//$(".bookPanel").css({ 'position': 'absolute', "top": parseInt($("#carousel").height()) });
$('#bottomLayer').css({ 'position': 'absolute', 'top': $("#carousel").height() });
$(".bookPanel").css({ "bottom": parseInt($(".bookPanel").height() - $("#carousel").height() + 28) });
$(".carouselShadow").css({ 'position': 'relative', "bottom": parseInt($(".carouselShadow").height() - $("#carousel").height()) });
//when having vertical scroll bar
//known issue: does not work for IE screen onresize, only works onload
if ($(window).height() != $(document).height()) {
//$("#roomreservations").html($(window).width() + ":" + $(document).width() + ":" + minWidth);
if ($(document).width() == minWidth && ($(window).width() != $(document).width())) {
//show horizontal scrollbar (by default)
}
else {
//otherwise hide horizontal scrollbar
$('html').css({ 'overflow-x': 'hidden' });
}
}
setTimeout('checkWidth(' + bgWrapperWidth + ')', 500);
readyToResize = true;
}
function checkWidth(bgWrapperWidth) {
$('#homePageMainPanel').width('100%');
$('#bottomLayer').width('100%');
$('#carousel').width($(document).width());
$("#carousel").children("img").each(function() {
if (($(document).height() - $('#bottomLayer').height()) >= $(this).height()) {
// Resize the image height to $("#background") height, as the image should fill from the top till the footer
$(this).css({ 'width': (($("#carousel").height() / $(this).height()) * $(this).width()), 'height': $("#carousel").height() });
}
});
}
function positionFooter() {
return null;
var footerPosition = $('#carousel').height() - $('#bottomLayer').height() + 1;
if ($('#carousel').height() < minHeight) {
footerPosition = minHeight - $('#carousel').height() + 1;
}
$('#carousel').css({ 'position': 'absolute', 'top': footerPosition });
$('html').css({ 'overflow': 'auto' });
$("#homePageMainPanel").css({ 'height': $('#carousel').height() });
}
var waitingTimeout;
function rotateBanner(param) {
var nextBanner = 0;
nextBanner = parseInt(currBanner) + 1;
if (nextBanner >= totalBanner) { nextBanner = 0; }
// wait until next bg image is fully loaded
if (imgReady[nextBanner] != true) {
waitingTimeout = window.setTimeout("rotateBanner('waiting')", timeWaiting);
return false;
}
clearTimeout(waitingTimeout);
transitionStart();
// cross fade
if (currBanner > -1) {
if (hybridMode) {
window.setTimeout("changeClass('quality','speed')", 500);
window.setTimeout("changeClass('speed','quality')", 1500);
}
fadeBgImg('#text_box_' + String(currBanner), 0, 500);
window.setTimeout("fadeBgImg('#img_box_" + String(currBanner) + "',0," + 1000 + ")", 500);
window.setTimeout("fadeBgImg('#img_box_" + String(nextBanner) + "',1," + 1000 + ")", 500);
window.setTimeout("fadeBgImg('#text_box_" + String(nextBanner) + "',1," + 1000 + ",true)", 1500);
window.setTimeout("transitionComplete()", 2500);
}
else {
if (hybridMode) {
changeClass('quality', 'speed');
window.setTimeout("changeClass('speed','quality')", 1000);
}
fadeBgImg("#img_box_" + String(nextBanner), 1, 1000);
window.setTimeout("fadeBgImg('#text_box_" + String(nextBanner) + "',1," + 1000 + ",true)", 1000);
window.setTimeout("showShadow()", 1000);
window.setTimeout("transitionComplete()", 2000);
}
currBanner = nextBanner;
}
function nextPaging(nextBanner) {
$('#carousel #paging ul li').each(function() {
if ($(this).attr('id') == 'paging_item_' + nextBanner) {
$(this).addClass("active");
}
else {
$(this).removeClass("active");
}
});
}
function changeClass(from, to) {
$("#carousel").removeClass(from).addClass(to);
}
function fadeBgImg(id, inout, duration, triggerTimer) {
$(id).stop(true, true);
if (inout == 1) {
$(id).fadeIn(duration);
}
else {
$(id).fadeOut(duration);
}
//$(id).animate({ 'opacity': inout }, duration);
if (triggerTimer == true) {
window.clearTimeout(theTimer);
if (totalBanner > 1) {
theTimer = window.setTimeout("rotateBanner()", timeTransInit + timeTransInterval);
}
}
}
function transitionStart() {
transitioning = true;
}
function transitionComplete() {
transitioning = false;
}
function Timer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function() {
start = new Date();
timerId = window.setTimeout(callback, remaining);
};
this.resume();
}
var waitingTimeout2;
function onBlur() {
//theTimer.pause();
clearTimeout(waitingTimeout2);
if (transitioning) {
waitingTimeout2 = window.setTimeout("onBlur()", timeWaiting);
return false;
}
window.clearTimeout(theTimer);
};
function onFocus() {
//theTimer.resume();
if (totalBanner > 1) {
window.clearTimeout(theTimer);
theTimer = window.setTimeout("rotateBanner()", timeTransInit + timeTransInterval);
}
};
if (/*#cc_on!#*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
readyToRotate = true;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
readyToRotate = true;
}
function showShadow() {
// Do not fade in shadow png IE8 and below
if ($.browser.msie && parseInt($.browser.version, 10) <= 8) {
$(".carouselShadow").delay(1000).show();
}
else {
$(".carouselShadow").delay(1000).fadeIn();
}
}
While it is great that you've built this yourself, someone has already solved all your problems with Backstretch.
Can someone give me a hand with this script? I wonder how to put in previous and next function? Start and stop function is working great. Hope that script is readable ok.
Another question.
Is it possible to make previous and next function like when you press previous bttn that script stops and you need to press play bttn to start it again?
Thanks for help.
<script type="text/javascript">
// SET THIS VARIABLE FOR DELAY, 1000 = 1 SECOND
var delayLength = 10000;
function doMove(panelWidth, tooFar) {
var leftValue = $("#mover").css("left");
// Fix for IE
if (leftValue == "auto") { leftValue = 0; };
var movement = parseFloat(leftValue, 10) - panelWidth;
if (movement == tooFar) {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": 0
}, function() {
$(".slide img").animate({
"top": 80
});
});
});
}
else {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": movement
}, function() {
$(".slide img").animate({
"top": 80
});
});
});
}
}
jQuery(function($){
var $slide1 = $("#slide-1");
var panelWidth = $slide1.css("width");
var panelPaddingLeft = $slide1.css("paddingLeft");
var panelPaddingRight = $slide1.css("paddingRight");
panelWidth = parseFloat(panelWidth, 10);
panelPaddingLeft = parseFloat(panelPaddingLeft, 10);
panelPaddingRight = parseFloat(panelPaddingRight, 10);
panelWidth = panelWidth + panelPaddingLeft + panelPaddingRight;
var numPanels = $(".slide").length;
var tooFar = -(panelWidth * numPanels);
var totalMoverwidth = numPanels * panelWidth;
$("#mover").css("width", totalMoverwidth);
$("#slider").append('Stop');
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$("#slider-stopper").click(function(){
if ($(this).text() == "Stop") {
clearInterval(sliderIntervalID);
$(this).text("Start");
}
else {
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$(this).text("Stop");
}
});
});
</script>