I need to scroll menus automatically when I am swiping the content left or right, for an eg.
when I am swiping to Right and coming to 5th panel slide the navigation should jumped to or scrolled to the 5th menu but now its stays or displays in menu 1 or whatever last menu was clicked only.
My expectation is to create like this eg.
https://js.devexpress.com/Demos/WidgetsGallery/Demo/Pivot/Overview/jQuery/iOS/
I am looking to Achieve two scenario, but I am failing and getting every time an error
If I Make the menu(selected menu) left or center side align then it should always be in left or center side align in initial load of the screen and also when I am swipe the slide content the menu should left or center align, sample eg. above link devexpress
When a content is swiped eg. 5th panel slide then the menu should scroll with respect to it
What I have tried is here and also the Jquery code html for reference
$(document).ready(function(){
$.fn.scrollpane = function(options) {
options = $.extend({
direction: "horizontal",
deadzone: 25,
useTransition: false,
desktop: true,
setupCss: true,
onscroll: function(pos, page, duration) {},
onscrollfinish: function(pos, page) {}
}, options);
var isTouch = "ontouchend" in document || !options.desktop,
onTouchstart = isTouch ? "touchstart" : "mousedown",
onTouchmove = isTouch ? "touchmove" : "mousemove",
onTouchend = isTouch ? "touchend" : "mouseup";
return this.each(function() {
// the scroll pane viewport
var outerElem = $(this);
// a large div containing the scrolling content
var innerElem = $("<div></div>");
innerElem.append(outerElem.children().remove());
outerElem.append(innerElem);
// cache these for later
var outerWidth = outerElem.width();
var outerHeight = outerElem.height();
// boolean
var horizontal = (options.direction === "horizontal");
// the number of pixels the user has to drag and release to trigger a page transition
// natural
var deadzone = Math.max(0, options.deadzone);
// the index of the current page. changed after the user completes each scrolling gesture.
// integer
var currentPage = 0;
// width of a page
// integer
var scrollUnit = horizontal ? outerWidth : outerHeight;
// x coordinate on the transform. -ve numbers go to the right,
// so this goes -ve as currentPage goes +ve
// integer (pixels)
var currentPos = 0;
// min and max scroll position:
// integer (pixels)
var scrollMax = 0;
var scrollMin = -scrollUnit * (innerElem.children().length - 1);
// time to settle after touched:
// natural (ms)
var settleTime = 200;
// dragMid and dragEnd are updated each frame of dragging:
// integer (pixels)
var dragStart = 0; // touch position when dragging starts
var dragMid = 0; // touch position on the last touchmove event
var dragEnd = 0; // touch position on this touchmove event
// +1 if dragging in +ve x direction, -1 if dragging in -ve x direction
// U(-1, +1)
var dragDir = 0;
if (options.setupCss) {
outerElem.css({
position: "relative",
overflow: "hidden"
});
// position the pages:
innerElem.children().each(function(index) {
$(this).css({
position: "absolute",
display: "block",
width: outerWidth,
height: outerHeight
}).css(horizontal ? "left" : "top", scrollUnit * index);
});
}
// natural natural boolean -> void
function scrollTo(position, duration, finish) {
var parameters = {};
parameters[(horizontal ? 'marginLeft' : 'marginTop')] = position;
options.onscroll(position, -position / scrollUnit, duration);
if (options.useTransition) {
innerElem.css({
transition: "none",
transform: horizontal ? ("translate3d(" + position + "px, 0, 0)") : ("translate3d(0, " + position + "px, 0)")
});
}
if (finish) {
if (!options.useTransition) {
innerElem.find('li').animate(parameters, duration);
} else {
innerElem.css({
transition: "all " + (duration === 0 ? "0" : duration + "ms")
});
}
setTimeout(function() {
options.onscrollfinish(position, -position / scrollUnit, duration);
});
} else if (!options.useTransition) {
innerElem.find('li').stop().css(parameters);
}
}
// Immediately set the 3D transform on the scroll pane.
// This causes Safari to create OpenGL resources to manage the animation.
// This sometimes causes a brief flicker, so best to do it at page load
// rather than waiting until the user starts to drag.
scrollTo(0, 0, true);
// bind the touch drag events:
outerElem.on(onTouchstart, function(e) {
e = isTouch ? e.originalEvent.touches[0] || e.originalEvent.changedTouches[0] : e;
dragStart = dragEnd = dragMid = horizontal ? e.pageX : e.pageY;
// bind the touch drag event:
$(this).on(onTouchmove, function(e) {
e = isTouch ? e.originalEvent.touches[0] || e.originalEvent.changedTouches[0] : e;
dragEnd = horizontal ? e.pageX : e.pageY;
dragDir = (dragEnd - dragMid) > 0 ? 1 : -1;
currentPos += dragEnd - dragMid;
dragMid = dragEnd;
scrollTo(currentPos, 0, false);
});
// bind the touch end event
}).on(onTouchend, function(e) {
// boolean
var reset = Math.abs(dragEnd - dragStart) < deadzone;
// real
var scrollPage = -1.0 * currentPos / scrollUnit;
// natural
var nextPage = reset ? currentPage : (dragDir < 0 ? Math.ceil(scrollPage) : Math.floor(scrollPage));
// int
var nextPos = Math.max(scrollMin, Math.min(scrollMax, -scrollUnit * nextPage));
currentPos = nextPos;
currentPage = nextPage;
scrollTo(nextPos, settleTime, true);
outerElem.off(onTouchmove);
});
// set up the menu callback:
outerElem.data("showpage", function(page) {
// int
page = page < 0 ? innerElem.children().length + page : page;
currentPos = Math.max(scrollMin, Math.min(scrollMax, -page * scrollUnit));
currentPage = -currentPos / scrollUnit;
scrollTo(currentPos, settleTime, true);
});
});
};
// Once you've initialized a scrollpane with $().scrollpane(),
// you can use this method to cause it to programmatically scroll
// to a particular page. Useful for creating a navigation menu, or
// those little dots on Apple-store-style product galleries.
//
// Pages are indexed from 0 upwards. Negative numbers can be used
// to index pages from the right.
//
// int -> jQuery
$.fn.showpage = function(index) {
var fn = this.data("showpage");
fn(index);
return this;
};
$(document).bind("touchmove", function() {
return false;
});
$(function() {
//$("#hpane").scrollpane();
$("#hpane").scrollpane({
// onscroll: function(pos, page, duration) {
// $("#pos").text(pos);
// $("#page").text(page);
// $("#snapping").text("no");
// },
onscrollfinish: function(pos, page) {
$("#pos").text(pos);
$("#page").text(page);
$("#snapping").text("yes");
$("ul.pager li").removeClass("active")
$("ul.pager li:nth-child("+(page+1)+")").addClass("active");
}
});
$("ul.pager li").click(function() {
var index = $(this).index();
$("ul.pager li").removeClass("active")
$(this).addClass("active");
$("#hpane").showpage(index);
//$("#vpane").showpage(index);
});
// $("input").click(function() {
// alert(this.value);
// });
});
});
Related
I found a javascript file which I used it for making a carousel in my website. But I want to make it responsive. So, I changed it. When you refresh page, it works well but when you rotate the page in mobile or tablet it could not match itself by new width and height. what is the problem?
$(".website_carousel").jCarouselLite({
btnNext: ".nexts",
btnPrev: ".prev",
visible:(($(window).width() > 481) ? "3" : "2")
})
here is the plugin I used for carousel
(function ($) { // Compliant with jquery.noConflict()
$.jCarouselLite = {
version: '1.1'
};
$.fn.jCarouselLite = function(options) {
options = $.extend({}, $.fn.jCarouselLite.options, options || {});
return this.each(function() { // Returns the element collection. Chainable.
var running,
animCss, sizeCss,
div = $(this), ul, initialLi, li,
liSize, ulSize, divSize,
numVisible, initialItemLength, itemLength, calculatedTo, autoTimeout;
initVariables(); // Set the above variables after initial calculations
initStyles(); // Set the appropriate styles for the carousel div, ul and li
initSizes(); // Set appropriate sizes for the carousel div, ul and li
attachEventHandlers(); // Attach event handlers for carousel to respond
function go(to) {
if(!running) {
clearTimeout(autoTimeout); // Prevents multiple clicks while auto-scrolling - edge case
calculatedTo = to;
if(options.beforeStart) { // Call the beforeStart() callback
options.beforeStart.call(this, visibleItems());
}
if(options.circular) { // If circular, and "to" is going OOB, adjust it
adjustOobForCircular(to);
} else { // If non-circular and "to" is going OOB, adjust it.
adjustOobForNonCircular(to);
} // If neither overrides "calculatedTo", we are not in edge cases.
animateToPosition({ // Animate carousel item to position based on calculated values.
start: function() {
running = true;
},
done: function() {
if(options.afterEnd) {
options.afterEnd.call(this, visibleItems());
}
if(options.auto) {
setupAutoScroll();
}
running = false;
}
});
if(!options.circular) { // Enabling / Disabling buttons is applicable in non-circular mode only.
disableOrEnableButtons();
}
}
return false;
}
function initVariables() {
running = false;
animCss = options.vertical ? "top" : "left";
sizeCss = options.vertical ? "height" : "width";
ul = div.find(">ul");
initialLi = ul.find(">li");
initialItemLength = initialLi.size();
// To avoid a scenario where number of items is just 1 and visible is 3 for example.
numVisible = initialItemLength < options.visible ? initialItemLength : options.visible;
if(options.circular) {
var $lastItemSet = initialLi.slice(initialItemLength-numVisible).clone();
var $firstItemSet = initialLi.slice(0,numVisible).clone();
ul.prepend($lastItemSet) // Prepend the lis with final items so that the user can click the back button to start with
.append($firstItemSet); // Append the lis with first items so that the user can click the next button even after reaching the end
options.start += numVisible; // Since we have a few artificial lis in the front, we will have to move the pointer to point to the real first item
}
li = $("li", ul);
itemLength = li.size();
calculatedTo = options.start;
}
function initStyles() {
div.css("visibility", "visible"); // If the div was set to hidden in CSS, make it visible now
li.css({
overflow: "hidden",
"float": options.vertical ? "none" : "left" // Some minification tools fail if "" is not used
});
ul.css({
margin: "0",
padding: "0",
position: "relative",
"list-style": "none",
"z-index": "1"
});
div.css({
overflow: "hidden",
position: "relative",
"z-index": "2",
});
// For a non-circular carousel, if the start is 0 and btnPrev is supplied, disable the prev button
if(!options.circular && options.btnPrev && options.start == 0) {
$(options.btnPrev).addClass("disabled");
}
}
function initSizes() {
var width_1 = div.width();
width_2=width_1/numVisible;
li.css({'width':width_2+'px'});
liSize = options.vertical ? // Full li size(incl margin)-Used for animation and to set ulSize
li.outerHeight(true) :
width_2;
ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items)
// Size of the entire UL. Including hidden and visible elements
// Will include LI's (width + padding + border + margin) * itemLength - Using outerwidth(true)
ul.css(sizeCss, ulSize+"px")
.css(animCss, -(calculatedTo * liSize));
// Width of the DIV. Only the width of the visible elements
// Will include LI's (width + padding + border + margin) * numVisible - Using outerwidth(true)
}
function attachEventHandlers() {
if(options.btnPrev) {
$(options.btnPrev).click(function() {
return go(calculatedTo - options.scroll);
});
}
if(options.btnNext) {
$(options.btnNext).click(function() {
return go(calculatedTo + options.scroll);
});
}
if(options.btnGo) {
$.each(options.btnGo, function(i, val) {
$(val).click(function() {
return go(options.circular ? numVisible + i : i);
});
});
}
if(options.mouseWheel && div.mousewheel) {
div.mousewheel(function(e, d) {
return d > 0 ?
go(calculatedTo - options.scroll) :
go(calculatedTo + options.scroll);
});
}
if(options.auto) {
setupAutoScroll();
}
}
function setupAutoScroll() {
autoTimeout = setTimeout(function() {
go(calculatedTo + options.scroll);
}, options.auto);
}
function visibleItems() {
return li.slice(calculatedTo).slice(0,numVisible);
}
function adjustOobForCircular(to) {
var newPosition;
// If first, then goto last
if(to <= options.start - numVisible - 1) {
newPosition = to + initialItemLength + options.scroll;
ul.css(animCss, -(newPosition * liSize) + "px");
calculatedTo = newPosition - options.scroll;
console.log("Before - Positioned at: " + newPosition + " and Moving to: " + calculatedTo);
}
// If last, then goto first
else if(to >= itemLength - numVisible + 1) {
newPosition = to - initialItemLength - options.scroll;
ul.css(animCss, -(newPosition * liSize) + "px");
calculatedTo = newPosition + options.scroll;
console.log("After - Positioned at: " + newPosition + " and Moving to: " + calculatedTo);
}
}
function adjustOobForNonCircular(to) {
// If user clicks "prev" and tries to go before the first element, reset it to first element.
if(to < 0) {
calculatedTo = 0;
}
// If "to" is greater than the max index that we can use to show another set of elements
// it means that we will have to reset "to" to a smallest possible index that can show it
else if(to > itemLength - numVisible) {
calculatedTo = itemLength - numVisible;
}
console.log("Item Length: " + itemLength + "; " +
"To: " + to + "; " +
"CalculatedTo: " + calculatedTo + "; " +
"Num Visible: " + numVisible);
}
function disableOrEnableButtons() {
$(options.btnPrev + "," + options.btnNext).removeClass("disabled");
$( (calculatedTo-options.scroll<0 && options.btnPrev)
||
(calculatedTo+options.scroll > itemLength-numVisible && options.btnNext)
||
[]
).addClass("disabled");
}
function animateToPosition(animationOptions) {
running = true;
ul.animate(
animCss == "left" ?
{ left: -(calculatedTo*liSize) } :
{ top: -(calculatedTo*liSize) },
$.extend({
duration: options.speed,
easing: options.easing
}, animationOptions)
);
}
});
};
$.fn.jCarouselLite.options = {
btnPrev: null, // CSS Selector for the previous button
btnNext: null, // CSS Selector for the next button
btnGo: null, // CSS Selector for the go button
mouseWheel: false, // Set "true" if you want the carousel scrolled using mouse wheel
auto: null, // Set to a numeric value (800) in millis. Time period between auto scrolls
speed: 200, // Set to a numeric value in millis. Speed of scroll
easing: null, // Set to easing (bounceout) to specify the animation easing
vertical: false, // Set to "true" to make the carousel scroll vertically
circular: true, // Set to "true" to make it an infinite carousel
visible: 3, // Set to a numeric value to specify the number of visible elements at a time
start: 0, // Set to a numeric value to specify which item to start from
scroll: 1, // Set to a numeric value to specify how many items to scroll for one scroll event
beforeStart: null, // Set to a function to receive a callback before every scroll start
afterEnd: null // Set to a function to receive a callback after every scroll end
};
})(jQuery);
The jquery library may be not working.Make sure you did include javascript Jquery library is correctly.
From the official documentation:
https://github.com/kswedberg/jquery-carousel-lite#responsive-carousels
Responsive Carousels
The responsive option is set to false by default. Once you set it to
true, you may want to set a few other options to get the desired
effect:
Everything automatic (autoCSS is true by default, so no need to add
it)
$('div.carousel').jCarouselLite({
// autoCSS: true,
autoWidth: true,
responsive: true
});
Everything manual (autoWidth is false by default, so no need to add
it)
Your best bet in this situation is to use CSS media queries.
$('div.carousel').jCarouselLite({
autoCSS: false,
// autoWidth: false,
responsive: true
});
// Bind your own handler to the refreshCarousel custom event, //
which is triggered when the window stops resizing
$('div.carousel').on('refreshCarousel', function() {
// do something
});
I want my social sidebar make scroll only within the gray div. I have already put the sidebar within the gray div does not exceed the footer or the content above. My difficulty is to sidebar scroll accompanying the scroll without going gray div.
http://test.eae.pt/beautyacademy/angebot/
JS:
beautyAcademy.sharer = {
element: void 0,
elementToScroll: void 0,
init:function() {
this.element = $('.js-sharer-ref');
console.log(this.element.length);
if(this.element.length != 1) {
return;
}
this.build();
},
build: function() {
this.binds();
},
binds: function() {
var _this = this;
// Element that's gonna scroll
this.$elementToScroll = $('.fixed-social');
// Element that's gonna scroll height
this.elementToScrollHeight = this.$elementToScroll.outerHeight();
// Element where scroll is gonna happen Height
this.elementHeight = this.element.outerHeight();
// Element where scroll is gonna happen distance to top
this.elementOffsetTop = this.element.offset().top;
// Scroll that was done on the page
this.windowScrollTop = $(window).scrollTop();
this.elementOffsetBottom = this.elementOffsetTop + this.elementHeight - this.elementToScrollHeight;
this.$elementToScroll.css('top', (_this.elementOffsetTop+80) + "px");
$(window).on('scroll', function() {
if(this.windowScrollTop + this.elementToScrollHeight < this.elementHeight )
this.$elementToScroll.css('margin-top', this.windowScrollTop );
});
}
};
You need to try like below :
$(function(){
if ($('#container').length) {
var el = $('#container');
var stickyTop = $('#container').offset().top; // returns number
var stickyHeight = $('#container').height();
$(window).scroll(function(){ // scroll event
var limit = $('#footer').offset().top - stickyHeight - 20;
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0 });
}
else {
el.css('position','static');
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});
DEMO
I'm trying to create a splash page similar to http://kinkinurbanthai.com/ but I need to re-activate the splash if the user is at the top of the page, and does an additional scroll up to 'request' or activate the splash again.
I have the code working up to the point of reactivating the splash element; but I can't get it to wait for the additional 'scroll up' request.
Here is the code so far that works, minus the locking b/c that isn't doing what I need it to atm. Code: http://jsfiddle.net/teejudp3/2/
// Does stuff on load and scrolls
//-------------------------------//
$(window).on("load scroll",function(e){
var $window = $(window);
if ( $window.scrollTop() <= 0 ) {
$('.splashwrapper').removeClass('remove');
}
// hide/show splash screen
//=========================//
// chrome/FF
$('.splashwrapper').bind('DOMMouseScroll', function(e){
// get scroll direction
var direction = (function () {
var delta = (e.type === 'DOMMouseScroll' ?
e.originalEvent.detail * -40 :
e.originalEvent.wheelDelta);
return delta > 0 ? 0 : 1;
}());
if( direction === 0 ) {
// scroll up
} else {
// scroll down
$('.splashwrapper').addClass('remove');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('.splashwrapper').bind('mousewheel', function(e){
// get scroll direction
var direction = (function () {
var delta = (e.type === 'DOMMouseScroll' ?
e.originalEvent.detail * -40 :
e.originalEvent.wheelDelta);
return delta > 0 ? 0 : 1;
}());
if( direction === 0 ) {
// scroll up
} else {
// scroll down
$('.splashwrapper').addClass('remove');
}
//prevent page fom scrolling
return false;
});
// touch device - uses touchSwipe.js
$(".splashwrapper").swipe({
swipeUp:function() {
$('.splashwrapper').addClass('remove');
}
});
});
I've tried to stop the users scroll if they go to <= 1 scroll top position but this doesn't seem to give the wanted affect.
// temporarily lock users scroll position
var $window = $(window), previousScrollTop = 1, scrollLock = false;
$window.scroll(function(event) {
if(scrollLock) {
$window.scrollTop(previousScrollTop);
}
previousScrollTop = $window.scrollTop();
});
// if at 1px from top, stop scroll from going up one time
if ( $window.scrollTop() <= 1 ) {
scrollLock = true;
$window.scrollTop( 1, 0);
setTimeout(function() {
scrollLock = false;
}, 1000);
}
Got this working by re-working the stop-point section - aka I was overthinking it.
Updated fiddle: http://jsfiddle.net/teejudp3/6/
var $window = $(window);
if ( $window.scrollTop() === 0 && $('.splashwrapper').hasClass('ready') ) {
$window.scrollTop(1);
$('.splashwrapper').removeClass('ready').removeClass('remove');
}
if ( $window.scrollTop() === 0 && !$('.splashwrapper').hasClass('ready') ) {
$window.scrollTop(1);
setTimeout(function() {
$('.splashwrapper').addClass('ready');
}, 500);
}
Goal:
Scroll the window smoothly with PageUp and PageDown keys.
1 press: page scrolls 1 unit.
n quick presses: page scrolls n units.
Let unit = 160px.
I press PageDown. Page starts scrolling to 160px, let's say it's 90px now, while I press PageDown again. It's obvious I don't want to STOP animation here, I want to change it's target frame to point to 320px! So it actually should speed up and NOT STOP until the page is scrolled to 320px.
It seemed obvious to me that all I have to do is changing tween object within step function given to .animate() method as argument.
I wired up second keydown to modify tween.end property, but it didn't work. Animation just stuttered and stopped. The movement always ends at first unit.
The x.stop().animate(...) approach is "no-no". More hickup - unacceptable. There must be a way to change animation end during the process without stopping it, slowing it down or any other unwanted artifacts.
Ok, here's the code:
var isScrolling = false;
var scrollStartPosition = 0;
var scrollTargetPosition = 0;
function goTo(position) {
if (isScrolling) {
scrollTargetPosition = position;
goToUpdate();
}
else {
scrollStartPosition = scrollTargetPosition = position;
position = position >= 0 ? (position <= pageEnd ? position : pageEnd) : 0;
$(page).animate({ scrollLeft : scroll = position }, { start: goToStart, step : goToStep, complete : goToComplete, duration : 500 });
}
}
function goToStart(arg) {
isScrolling = true;
}
function goToUpdate() {
// ???
}
function goToStep(n, tween) {
isScrolling = true;
if (scrollTargetPosition !== scrollStartPosition) {
scrollStartPosition = tween.end = scrollTargetPosition;
}
}
function goToComplete(arg) {
isScrolling = false;
}
Please, help :) I've wasted ca 8h experimenting with this with no luck. jQuery.animate() seems completely ignoring any atempt to change animation in progress, the only thing I succeeded to do is to stop and restart it. I also managed to queue subsequent moves, but the total movement was just FUGLY n jumps instead one normal move.
I've just described how to do it for free ;) It actually works as expected, I missed one very ugly bug in position parameter calculation. It just didn't change with pressing the keys.
Here's fixed goTo() function:
function goTo(position) {
if (isScrolling) {
scroll = scrollTargetPosition = position;
goToUpdate();
}
else {
scrollStartPosition = scrollTargetPosition = position;
position = position >= 0 ? (position <= pageEnd ? position : pageEnd) : 0;
$(page).animate({ scrollLeft : scroll = position }, { start: goToStart, step : goToStep, complete : goToComplete, duration : 500, queue : false });
}
}
The only difference is scroll variable (defined elsewhere) set to the new position after registering the event.
Now it works beautifully.
BTW, if we want use that kind of effect without breaking accessibility - it should be activated with some conditions met first. In my code the screen resoultion is checked. If it's over 1280px wide - I activate special animated view.
So, here's complete solution:
// create a very wide page
// include jQuery and this...
var page;
var pageEnd;
var scroll;
var scrollStep = 160;
var isScrolling = false;
var scrollStartPosition = 0;
var scrollTargetPosition = 0;
function goTo(position) {
if (isScrolling) {
scroll = scrollTargetPosition = position;
}
else {
scrollStartPosition = scrollTargetPosition = position;
position = position >= 0 ? (position <= pageEnd ? position : pageEnd) : 0;
$(page).animate({ scrollLeft : scroll = position }, { start: goToStart, step : goToStep, complete : goToComplete, duration : 500, queue : false });
}
}
function goToStart(arg) {
isScrolling = true;
}
function goToStep(n, tween) {
isScrolling = true;
if (scrollTargetPosition !== scrollStartPosition) {
scrollStartPosition = tween.end = scrollTargetPosition;
}
}
function goToComplete(arg) {
isScrolling = false;
}
function keyDown(e) {
var handled = true;
switch (e.which) {
case 33:
case 38:
goTo(scroll - scrollStep);
break;
case 34:
case 40:
goTo(scroll + scrollStep);
break;
case 35:
goTo(pageEnd);
break;
case 36:
goTo(0);
break;
default:
handled = false;
break;
}
if (handled) e.preventDefault();
}
function init() {
page = $('body');
pageEnd = page[0].scrollWidth - page[0].clientWidth;
page.scrollLeft(1);
if (page.scrollLeft() < 1) page = $('html');
goTo(0);
$('html').css({
'overflow-x' : 'scroll',
'overflow-y' : 'hidden'
});
scroll = page.scrollLeft();
$(window).keydown(keyDown);
}
$(init);
example page
I have a floating menu that i've built to the left side (green),
and i've made it start moving after 200 pixels. and now i need to to stop
and not go over the footer (blue) area.
any ideas how to make my JS better?
this thing is, I cannot check this on the scroll event, because of the animation
going on after i scroll, so it needs to be done someway else.
so how to make the animation stop at the end just before the footer?
I've resolved the issue perfectly (hope so)
with the help of you guys, and released
a jQuery plugin for floating sticky boxes:
http://plugins.jquery.com/project/stickyfloat
$.fn.menuFloater = function(options) {
var opts = $.extend({ startFrom: 0, offsetY: 0, attach: '', duration: 50 }, options);
// opts.offsetY
var $obj = this;
$obj.css({ position: 'absolute' /*, opacity: opts.opacity */ });
/* get the bottom position of the parent element */
var parentBottomPoint = $obj.parent().offset().top + $obj.parent().height() ;
var topMax = $obj.parent().height() - $obj.innerHeight() + parseInt($obj.parent().css('padding-top')); //get the maximum scrollTop value
if ( topMax < 0 ) {
topMax = 0;
}
console.log(topMax);
$(window).scroll(function () {
$obj.stop(); // stop all calculations on scroll event
// console.log($(document).scrollTop() + " : " + $obj.offset().top);
/* get to bottom position of the floating element */
var isAnimated = true;
var objTop= $obj.offset().top;
var objBottomPoint = objTop + $obj.outerHeight();
if ( ( $(document).scrollTop() > opts.startFrom || (objTop - $(document).scrollTop()) > opts.startFrom ) && ( $obj.outerHeight() < $(window).height() ) ){
var adjust;
( $(document).scrollTop() < opts.startFrom ) ? adjust = opts.offsetY : adjust = -opts.startFrom + opts.offsetY;
// and changed here to take acount the maximum scroll top value
var newpos = ($(document).scrollTop() + adjust );
if ( newpos > topMax ) {
newpos = topMax;
}
$obj.animate({ top: newpos }, opts.duration, function(){ isAnimated = false } );
}
else {
$obj.stop();
}
});
};
In the $(window).scroll function have you checked whether the bottom position of the floating div is less than or equal to the top position of the footer element.