Centering a div in firefox with jQuery - javascript

So I am attempting to use the following code to center a div in the window using jQuery:
(function($) {
$.fn.extend({
center: function(options) {
var options = $.extend({ // Default values
inside: window,
// element, center into window
transition: 0,
// millisecond, transition time
minX: 0,
// pixel, minimum left element value
minY: 0,
// pixel, minimum top element value
withScrolling: true,
// booleen, take care of the scrollbar (scrollTop)
vertical: true,
// booleen, center vertical
horizontal: true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {
position: 'absolute'
};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {
top: top + 'px'
});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {
left: left + 'px'
});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);​
This works fine in Chrome but it doesn't seem to vertically center in firefox and I can't figure what I am doing wrong. Is there a bug with firefox that would render it unable to calculate the window height?

I can't remember what I've changed but here it is:
$.fn.extend({
center: function(options) {
var options = $.extend({ // Default values
inside: window,
// element, center into window
transition: 0,
// millisecond, transition time
minX: 0,
// pixel, minimum left element value
minY: 0,
// pixel, minimum top element value
withScrolling: true,
// booleen, take care of the scrollbar (scrollTop)
vertical: true,
// booleen, center vertical
horizontal: true // booleen, center horizontal
}, options);
$(this).each(function() {
var props = {
position: 'absolute'
};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {
top: top + 'px'
});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {
left: left + 'px'
});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
});
return $(this);
}
});
It seems to work fine in firefox: http://jsfiddle.net/NQRUF/4/

Try this:
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
Usage:
$(element).center();
Source

Related

jQuery: Animate Removal of Style Attribute from Multiple divs

I have ~33 divs that I am setting the position of randomly and animating this places. These divs are originally positioned with the help of flex and then the positions are randomized by setting their positions to relative and changing the left and top values. This happens every click.
On every alternate click, I want to return the divs to their normal position. So far the only solution to this I've found is the .removeAttr('style') method. However, I want to be able to animate their return to original position. Is this possible?
Here is the code:
var position_checker = false;
$(document).click(function() {
if(position_checker == false) {
$('.poster05-text').each(function() {
var position = $(this).offset();
$(this).css({
position: 'relative',
}, position);
var docHeight = $(document).height(),
docWidth = $(document).width(),
divWidth = 500,
divHeight = 500,
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
var posLeft = Math.floor(Math.random() * widthMax);
var posTop = Math.floor(Math.random() * heightMax);
// console.log(docHeight, docWidth);
$(this).animate({
position: 'fixed',
left: posLeft,
top: posTop
}, 1000 , 'easeInQuint');
});
position_checker=true;
}
else if(position_checker==true) {
$('.poster05-text').each(function() {
$(this).removeAttr('style');
});
position_checker=false;
}
});
I don't know this a right way to do that or not .. but anyway .. you need to save the previous left and top positions for each div on array
var position_checker = false , T_L_Positions = [];
$(document).click(function() {
if(position_checker == false) {
$('.poster05-text').each(function(i) {
var position = $(this).offset();
$(this).css({
position: 'relative',
}, position);
T_L_Positions[i] = new Array(position.top ,position.left);
var docHeight = $(document).height(),
docWidth = $(document).width(),
divWidth = 500,
divHeight = 500,
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
var posLeft = Math.floor(Math.random() * widthMax);
var posTop = Math.floor(Math.random() * heightMax);
// console.log(docHeight, docWidth);
$(this).animate({
position: 'fixed',
left: posLeft,
top: posTop
}, 1000 , 'easeInQuint');
});
position_checker=true;
}
else if(position_checker==true) {
$('.poster05-text').each(function(i) {
$(this).animate({
position: 'relative',
left: T_L_Positions[i][1],
top: T_L_Positions[i][0]
}, 1000 , 'easeInQuint');
});
position_checker=false;
}
});
Note: This Code Not Tested .. but you can try it
maybe you'll need to wrap your code in $(document).ready(function(){ //code here })
If you're looking for a non-JS solution. You should be able to use CSS Transitions to do this.
transition: top 500ms, left 300ms;
That way you can just set and remove the position and let CSS deal with the animation.
For more information check out these examples:
https://www.w3schools.com/css/css3_transitions.asp
https://css-tricks.com/almanac/properties/t/transition/

slimScroll scrolls to fast (wheelStep and touchScrollStep not working)

I'm using slimScroll within a js project for a scroll bar on one side of the page. There are a lot of elements within the the scrollView and right now it's scrolling way to quickly and not intuitively. When I reduce the amount of wheel and/or touchScrollStep there is not change it speed.
* Version: 1.3.0
*
*/
(function($) {
jQuery.fn.extend({
slimScroll: function(options) {
var defaults = {
// width in pixels of the visible scroll area
width : 'auto',
// height in pixels of the visible scroll area
height : '250px',
// width in pixels of the scrollbar and rail
size : '7px',
// scrollbar color, accepts any hex/color value
color: '#000',
// scrollbar position - left/right
position : 'right',
// distance in pixels between the side edge and the scrollbar
distance : '1px',
// default scroll position on load - top / bottom / $('selector')
start : 'top',
// sets scrollbar opacity
opacity : .4,
// enables always-on mode for the scrollbar
alwaysVisible : false,
// check if we should hide the scrollbar when user is hovering over
disableFadeOut : false,
// sets visibility of the rail
railVisible : false,
// sets rail color
railColor : '#333',
// sets rail opacity
railOpacity : .2,
// whether we should use jQuery UI Draggable to enable bar dragging
railDraggable : true,
// defautlt CSS class of the slimscroll rail
railClass : 'slimScrollRail',
// defautlt CSS class of the slimscroll bar
barClass : 'slimScrollBar',
// defautlt CSS class of the slimscroll wrapper
wrapperClass : 'slimScrollDiv',
// check if mousewheel should scroll the window if we reach top/bottom
allowPageScroll : false,
// scroll amount applied to each mouse wheel step
wheelStep : 20,
// scroll amount applied when user is using gestures
touchScrollStep : 200,
// sets border radius
borderRadius: '7px',
// sets border radius of the rail
railBorderRadius : '7px'
};
var o = $.extend(defaults, options);
// do it for every element that matches selector
this.each(function(){
var isOverPanel, isOverBar, isDragg, queueHide, touchDif,
barHeight, percentScroll, lastScroll,
divS = '<div></div>',
minBarHeight = 30,
releaseScroll = false;
// used in event handlers and for better minification
var me = $(this);
// ensure we are not binding it again
if (me.parent().hasClass(o.wrapperClass))
{
// start from last bar position
var offset = me.scrollTop();
// find bar and rail
bar = me.parent().find('.' + o.barClass);
rail = me.parent().find('.' + o.railClass);
getBarHeight();
// check if we should scroll existing instance
if ($.isPlainObject(options))
{
// Pass height: auto to an existing slimscroll object to force a resize after contents have changed
if ( 'height' in options && options.height == 'auto' ) {
me.parent().css('height', 'auto');
me.css('height', 'auto');
var height = me.parent().parent().height();
me.parent().css('height', height);
me.css('height', height);
}
if ('scrollTo' in options)
{
// jump to a static point
offset = parseInt(o.scrollTo);
}
else if ('scrollBy' in options)
{
// jump by value pixels
offset += parseInt(o.scrollBy);
}
else if ('destroy' in options)
{
// remove slimscroll elements
bar.remove();
rail.remove();
me.unwrap();
return;
}
// scroll content by the given offset
scrollContent(offset, false, true);
}
return;
}
// optionally set height to the parent's height
o.height = (o.height == 'auto') ? me.parent().height() : o.height;
// wrap content
var wrapper = $(divS)
.addClass(o.wrapperClass)
.css({
position: 'relative',
overflow: 'hidden',
width: o.width,
height: o.height
});
// update style for the div
me.css({
overflow: 'hidden',
width: o.width,
height: o.height
});
// create scrollbar rail
var rail = $(divS)
.addClass(o.railClass)
.css({
width: o.size,
height: '100%',
position: 'absolute',
top: 0,
display: (o.alwaysVisible && o.railVisible) ? 'block' : 'none',
'border-radius': o.railBorderRadius,
background: o.railColor,
opacity: o.railOpacity,
zIndex: 90
});
// create scrollbar
var bar = $(divS)
.addClass(o.barClass)
.css({
background: o.color,
width: o.size,
position: 'absolute',
top: 0,
opacity: o.opacity,
display: o.alwaysVisible ? 'block' : 'none',
'border-radius' : o.borderRadius,
BorderRadius: o.borderRadius,
MozBorderRadius: o.borderRadius,
WebkitBorderRadius: o.borderRadius,
zIndex: 99
});
// set position
var posCss = (o.position == 'right') ? { right: o.distance } : { left: o.distance };
rail.css(posCss);
bar.css(posCss);
// wrap it
me.wrap(wrapper);
// append to parent div
me.parent().append(bar);
me.parent().append(rail);
// make it draggable and no longer dependent on the jqueryUI
if (o.railDraggable){
bar.bind("mousedown", function(e) {
var $doc = $(document);
isDragg = true;
t = parseFloat(bar.css('top'));
pageY = e.pageY;
$doc.bind("mousemove.slimscroll", function(e){
currTop = t + e.pageY - pageY;
bar.css('top', currTop);
scrollContent(0, bar.position().top, false);// scroll content
});
$doc.bind("mouseup.slimscroll", function(e) {
isDragg = false;hideBar();
$doc.unbind('.slimscroll');
});
return false;
}).bind("selectstart.slimscroll", function(e){
e.stopPropagation();
e.preventDefault();
return false;
});
}
// on rail over
rail.hover(function(){
showBar();
}, function(){
hideBar();
});
// on bar over
bar.hover(function(){
isOverBar = true;
}, function(){
isOverBar = false;
});
// show on parent mouseover
me.hover(function(){
isOverPanel = true;
showBar();
hideBar();
}, function(){
isOverPanel = false;
hideBar();
});
// support for mobile
me.bind('touchstart', function(e,b){
if (e.originalEvent.touches.length)
{
// record where touch started
touchDif = e.originalEvent.touches[0].pageY;
}
});
me.bind('touchmove', function(e){
// prevent scrolling the page if necessary
if(!releaseScroll)
{
e.originalEvent.preventDefault();
}
if (e.originalEvent.touches.length)
{
// see how far user swiped
var diff = (touchDif - e.originalEvent.touches[0].pageY) / o.touchScrollStep;
// scroll content
scrollContent(diff, true);
touchDif = e.originalEvent.touches[0].pageY;
}
});
// set up initial height
getBarHeight();
// check start position
if (o.start === 'bottom')
{
// scroll content to bottom
bar.css({ top: me.outerHeight() - bar.outerHeight() });
scrollContent(0, true);
}
else if (o.start !== 'top')
{
// assume jQuery selector
scrollContent($(o.start).position().top, null, true);
// make sure bar stays hidden
if (!o.alwaysVisible) { bar.hide(); }
}
// attach scroll events
attachWheel();
function _onWheel(e)
{
// use mouse wheel only when mouse is over
if (!isOverPanel) { return; }
var e = e || window.event;
var delta = 0;
if (e.wheelDelta) { delta = -e.wheelDelta/120; }
if (e.detail) { delta = e.detail / 3; }
var target = e.target || e.srcTarget || e.srcElement;
if ($(target).closest('.' + o.wrapperClass).is(me.parent())) {
// scroll content
scrollContent(delta, true);
}
// stop window scroll
if (e.preventDefault && !releaseScroll) { e.preventDefault(); }
if (!releaseScroll) { e.returnValue = false; }
}
function scrollContent(y, isWheel, isJump)
{
releaseScroll = false;
var delta = y;
var maxTop = me.outerHeight() - bar.outerHeight();
if (isWheel)
{
// move bar with mouse wheel
delta = parseInt(bar.css('top')) + y * parseInt(o.wheelStep) / 100 * bar.outerHeight();
// move bar, make sure it doesn't go out
delta = Math.min(Math.max(delta, 0), maxTop);
// if scrolling down, make sure a fractional change to the
// scroll position isn't rounded away when the scrollbar's CSS is set
// this flooring of delta would happened automatically when
// bar.css is set below, but we floor here for clarity
delta = (y > 0) ? Math.ceil(delta) : Math.floor(delta);
// scroll the scrollbar
bar.css({ top: delta + 'px' });
}
// calculate actual scroll amount
percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight());
delta = percentScroll * (me[0].scrollHeight - me.outerHeight());
if (isJump)
{
delta = y;
var offsetTop = delta / me[0].scrollHeight * me.outerHeight();
offsetTop = Math.min(Math.max(offsetTop, 0), maxTop);
bar.css({ top: offsetTop + 'px' });
}
// scroll content
me.scrollTop(delta);
// fire scrolling event
me.trigger('slimscrolling', ~~delta);
// ensure bar is visible
showBar();
// trigger hide when scroll is stopped
hideBar();
}
function attachWheel()
{
if (window.addEventListener)
{
this.addEventListener('DOMMouseScroll', _onWheel, false );
this.addEventListener('mousewheel', _onWheel, false );
this.addEventListener('MozMousePixelScroll', _onWheel, false );
}
else
{
document.attachEvent("onmousewheel", _onWheel)
}
}
function getBarHeight()
{
// calculate scrollbar height and make sure it is not too small
barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight);
bar.css({ height: barHeight + 'px' });
// hide scrollbar if content is not long enough
var display = barHeight == me.outerHeight() ? 'none' : 'block';
bar.css({ display: display });
}
function showBar()
{
// recalculate bar height
getBarHeight();
clearTimeout(queueHide);
// when bar reached top or bottom
if (percentScroll == ~~percentScroll)
{
//release wheel
releaseScroll = o.allowPageScroll;
// publish approporiate event
if (lastScroll != percentScroll)
{
var msg = (~~percentScroll == 0) ? 'top' : 'bottom';
me.trigger('slimscroll', msg);
}
}
else
{
releaseScroll = false;
}
lastScroll = percentScroll;
// show only when required
if(barHeight >= me.outerHeight()) {
//allow window scroll
releaseScroll = true;
return;
}
bar.stop(true,true).fadeIn('fast');
if (o.railVisible) { rail.stop(true,true).fadeIn('fast'); }
}
function hideBar()
{
// only hide when options allow it
if (!o.alwaysVisible)
{
queueHide = setTimeout(function(){
if (!(o.disableFadeOut && isOverPanel) && !isOverBar && !isDragg)
{
bar.fadeOut('slow');
rail.fadeOut('slow');
}
}, 1000);
}
}
});
// maintain chainability
return this;
}
});
jQuery.fn.extend({
slimscroll: jQuery.fn.slimScroll
});
})(jQuery);
I've just played around with this script and I kept adjusting the numbers and these are the numbers that felt more natural to me.
wheelStep : 10,
touchScrollStep : 75
The only thing I'm not happy with is how it doesn't understand how fast you scrolled with touch events, so it doesn't have that inertia effect like native iOS does naturally. I'm hoping they'll add that option soon.
Find
delta = (y > 0) ? Math.ceil(delta): Math.floor(delta);
and change it to the following:
var speedfix = 10;
delta = (y > 0) ? Math.ceil(delta) + speedfix : Math.floor(delta)- speedfix;
Change the value of speedfix to your requirement

Auto scrolling to element in scrollable div

I have 5 elements that are within a div larger than the screen (on a mobile phone).
I want the user to be able to click on one of the elements and have that element scroll to the centre of the screen.
I've tried writing this with jQuery myself, but I can't seem to get the logic quite right. I've got it kind of moving but the element selected doesn't go to the centre of the screen.
Here's a Fiddle of what I have do far: http://jsfiddle.net/geQ64/1/
Here's the JS from the fiddle also:
$(window).on('load', function() {
$('.tab-3').trigger('click');
var width = $(window).width();
if (width < 651) {
$('.ul-wrap').scrollLeft( $('.tab-3').offset().left );
}
});
$('.single-tabs').on('click', function() {
var offset = $('.tabs').width();
offset = offset/5;
var center = offset/2;
var tab = $(this).data('tab');
$('.tabs-content').hide();
$('.tab'+ tab +'').show();
var width = $(window).width();
if (width > 650) {
var arrow = tab*20-12;
$('.arrow-up').css('margin-left', '' + arrow + '%');
} else {
tab = tab - 1;
var position = offset * tab - center;
$('.ul-wrap').scrollLeft(position);
}
});
Found a fix, here's the JS is anyone needs it.
The - 55 in the var position is for an arrow that sits in the centre of the page below the elements I'm moving with this script.
$(window).on('load', function() {
$('.tab-3').trigger('click');
var width = $(window).width();
if (width < 651) {
var offset = $('.tabs').width();
offset = offset/7;
var center = offset/2;
var position = offset * 2 + center - 50;
$('.ul-wrap').animate({
scrollLeft: position
}, 200);
}
});
$('.single-tabs').on('click', function() {
var offset = $('.tabs').width();
offset = offset/7;
var center = offset/2;
var tab = $(this).data('tab');
$('.tabs-content').hide();
$('.tab'+ tab +'').show();
var width = $(window).width();
if (width > 650) {
var arrow = tab*20-12;
$('.arrow-up').css('margin-left', '' + arrow + '%');
} else {
tab = tab - 1;
var position = offset * tab + center - 50;
$('.ul-wrap').animate({
scrollLeft: position
}, 200);
}

position:fixed navigation stop at end of specific div - parallax scrolling & javascript

I have a vertically oriented vertical navigation bar, that I would like to make stop at the end of #contact. It will need to resume scrolling again if the user scrolls back up.
What is the best way to achieve this?
javascript being used:
$(function() {
$.fn.scrollBottom = function() {
return $(document).height() - this.scrollTop() - this.height();
};
var $el = $('#nav>div');
var $window = $(window);
var top = $el.parent().position().top;
$window.bind("scroll resize", function() {
var gap = $window.height() - $el.height() - 10;
var visibleFoot = 340 - $window.scrollBottom();
var scrollTop = $window.scrollTop()
if (scrollTop < top + 10) {
$el.css({
top: (top - scrollTop) + "px",
bottom: "auto"
});
} else if (visibleFoot > gap) {
$el.css({
top: "auto",
bottom: visibleFoot + "px"
});
} else {
$el.css({
top: 0,
bottom: "auto"
});
}
}).scroll();
});
jsfiddle
I believe this is the code you are looking for:
$(function() {
var $Nav = $('#Nav');
var $window = $(window);
var $contact = $('#contact');
var maxTop = $contact.offset().top + $contact.height() - $Nav.height();
window.navFixed = 1;
$window.bind("scroll resize", function() {
var currentTop = $window.scrollTop();
if (currentTop <= maxTop && window.navFixed == 0) {
$Nav.css({
position: 'fixed',
top: '5%'
});
window.navFixed = 1;
} else if (currentTop > maxTop && window.navFixed == 1) {
$Nav.css({
position: 'absolute',
top: maxTop
});
window.navFixed = 0;
}
}).scroll();
});
The #Nav element contains the CSS you had originally specified: position: fixed; top: (...). When the document is ready, the variable maxTop is calculated based on the #contact element's top and height.
On the scroll and resize event, the variable currentTop is calculated as the current scroll position. If this value is lower than maxTop, then #Nav is set to the original CSS; if the value is higher, new CSS styles are applied: position: absolute; top: maxTop;
window.navFixed is used to prevent the CSS to be constantly updated while scrolling. I'm sure that bit can be improved, however, it demonstrates its purpose.
Check out the JSFiddle for the full HTML..
PS. There's a minor bug in your code, where #Nav refers to the <ul> element, rather than the <nav> element. However, the moving element is the <ul>, when it should be <nav>.

jQuery: How can I edit this code to produce a fade effect instead of a sliding effect?

I'm having trouble making the following code fade an image instead of sliding an image. Any assistance would be much appreciated.
Here's the code:
var rotate_delay = 7000;
(function($) {
$.fn.preload = function(options) {
var opts = $.extend({}, $.fn.preload.defaults, options);
o = $.meta ? $.extend({}, opts, this.data()) : opts;
var c = this.length,
l = 0;
return this.each(function() {
var $i = $(this);
$('<img/>').load(function(i){
++l;
if(l == c) o.onComplete();
}).attr('src',$i.attr('src'));
});
};
$.fn.preload.defaults = {
onComplete : function(){return false;}
};
})(jQuery);
$(function() {
var $tf_bg = $('#tf_bg'),
$tf_bg_images = $tf_bg.find('img'),
$tf_bg_img = $tf_bg_images.eq(0),
$tf_thumbs = $('#tf_thumbs'),
total = $tf_bg_images.length,
current = 0,
$tf_content_wrapper = $('#tf_content_wrapper'),
$tf_next = $('#tf_next'),
$tf_prev = $('#tf_prev'),
$tf_loading = $('#tf_loading');
//preload the images
$tf_bg_images.preload({
onComplete : function(){
$tf_loading.hide();
init();
}
});
//shows the first image and initializes events
function init(){
//get dimentions for the image, based on the windows size
var dim = getImageDim($tf_bg_img);
//set the returned values and show the image
$tf_bg_img.css({
width : dim.width,
height : dim.height,
left : dim.left,
top : dim.top
}).fadeIn();
//resizing the window resizes the $tf_bg_img
$(window).bind('resize',function(){
var dim = getImageDim($tf_bg_img);
$tf_bg_img.css({
width : dim.width,
height : dim.height,
left : dim.left,
top : dim.top
});
});
//expand and fit the image to the screen
$('#tf_zoom').live('click',
function(){
if($tf_bg_img.is(':animated'))
return false;
var $this = $(this);
if($this.hasClass('tf_zoom')){
resize($tf_bg_img);
$this.addClass('tf_fullscreen')
.removeClass('tf_zoom');
}
else{
var dim = getImageDim($tf_bg_img);
$tf_bg_img.animate({
width : dim.width,
height : dim.height,
top : dim.top,
left : dim.left
},350);
$this.addClass('tf_zoom')
.removeClass('tf_fullscreen');
}
}
);
var rotate_timeout;
//click the arrow down, scrolls down
$tf_next.bind('click',function(){
if($tf_bg_img.is(':animated'))
return false;
clearInterval(rotate_timeout);
scroll('tb');
});
//click the arrow up, scrolls up
$tf_prev.bind('click',function(){
if($tf_bg_img.is(':animated'))
return false;
clearInterval(rotate_timeout);
scroll('bt');
});
function rotate()
{
if($tf_bg_img.is(':animated'))
return false;
scroll('tb');
}
rotate_timeout = setInterval(rotate, rotate_delay);
//mousewheel events - down / up button trigger the scroll down / up
$(document).mousewheel(function(e, delta) {
if($tf_bg_img.is(':animated'))
return false;
if(delta > 0)
scroll('bt');
else
scroll('tb');
return false;
});
//key events - down / up button trigger the scroll down / up
$(document).keydown(function(e){
if($tf_bg_img.is(':animated'))
return false;
switch(e.which){
case 38:
scroll('bt');
break;
case 40:
scroll('tb');
break;
}
});
}
//show next / prev image
function scroll(dir){
//if dir is "tb" (top -> bottom) increment current,
//else if "bt" decrement it
current = (dir == 'tb')?current + 1:current - 1;
//we want a circular slideshow,
//so we need to check the limits of current
if(current == total) current = 0;
else if(current < 0) current = total - 1;
//flip the thumb
$tf_thumbs.flip({
direction : dir,
speed : 400,
onBefore : function(){
//the new thumb is set here
var content = '<span id="tf_zoom" class="tf_zoom"> </span>';
content +='<img src="' + $tf_bg_images.eq(current).attr('longdesc') + '" alt="Thumb' + (current+1) + '"/>';
$tf_thumbs.html(content);
}
});
//we get the next image
var $tf_bg_img_next = $tf_bg_images.eq(current),
//its dimentions
dim = getImageDim($tf_bg_img_next),
//the top should be one that makes the image out of the viewport
//the image should be positioned up or down depending on the direction
top = (dir == 'tb')?$(window).height() + 'px':-parseFloat(dim.height,10) + 'px';
//set the returned values and show the next image
$tf_bg_img_next.css({
width : dim.width,
height : dim.height,
left : dim.left,
top : top
}).show();
//now slide it to the viewport
$tf_bg_img_next.stop().animate({
top : dim.top
},1000);
//we want the old image to slide in the same direction, out of the viewport
var slideTo = (dir == 'tb')?-$tf_bg_img.height() + 'px':$(window).height() + 'px';
$tf_bg_img.stop().animate({
top : slideTo
},1000,function(){
//hide it
$(this).hide();
//the $tf_bg_img is now the shown image
$tf_bg_img = $tf_bg_img_next;
//show the description for the new image
var desc = $tf_content_wrapper.children().eq(current);
jQuery("h2, p",desc).css("opacity", 0);
var speed = 1000, titlesFactor = 0, titlespeed = 1000, titleeasing = 'swing';
desc.show()
.find('h2')
.css('left', -50 + 'px' )
.stop()
.delay( speed * titlesFactor )
.animate({ left : 0 + 'px', opacity : 1 }, titlespeed, titleeasing)
.end()
.find('p')
.css( 'left', 50 + 'px' )
.stop()
.delay( speed * titlesFactor )
.animate({ left : 0 + 'px', opacity : 1 }, titlespeed, titleeasing)
.end();
});
//hide the current description
$tf_content_wrapper.children(':visible')
.hide()
}
//animate the image to fit in the viewport
function resize($img){
var w_w = $(window).width(),
w_h = $(window).height(),
i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w,
new_w,new_h;
if(i_w > i_h){
new_w = w_w;
new_h = w_w * r_i;
if(new_h > w_h){
new_h = w_h;
new_w = w_h / r_i;
}
}
else{
new_h = w_w * r_i;
new_w = w_w;
}
$img.animate({
width : new_w + 'px',
height : new_h + 'px',
top : '0px',
left : '0px'
},350);
}
//get dimentions of the image,
//in order to make it full size and centered
function getImageDim($img){
var w_w = $(window).width(),
w_h = $(window).height(),
r_w = w_h / w_w,
i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w,
new_w,new_h,
new_left,new_top;
if(r_w > r_i){
new_h = w_h;
new_w = w_h / r_i;
}
else{
new_h = w_w * r_i;
new_w = w_w;
}
return {
width : new_w + 'px',
height : new_h + 'px',
left : (w_w - new_w) / 2 + 'px',
top : (w_h - new_h) / 2 + 'px'
};
}
});
This isn't my code, I'm trying to make edits so that it will achieve the effect that I am after, i.e. fade
Thanks again.
You can replace the show() with fadeIn(timeout) and the hide() with fadeOut(timeout).

Categories

Resources