Making JavaScript Custom ScrollBar - javascript

I said “JavaScript”. I'm trying to make my own JavaScript custom scrollbar. It's almost successful. The problem is that I can't get an accurate multiplier for the scrolling speed. This is my code:
var elem = document.getElementById('scroll-area'),
track = elem.children[1],
thumb = track.children[0],
height = parseInt(elem.offsetHeight, 10),
cntHeight = parseInt(elem.children[0].offsetHeight, 10),
trcHeight = parseInt(track.offsetHeight, 10),
distance = cntHeight - height,
mean = 50, // For multiplier (go faster or slower)
current = 0;
elem.children[0].style.top = current + "px"; // Set default `top` value as `0` for initiation
thumb.style.height = Math.round(trcHeight * height / cntHeight) + 'px'; // Set the scrollbar thumb hight
var doScroll = function (e) {
// cross-browser wheel delta
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
// (1 = scroll-up, -1 = scroll-down)
// Always check the scroll distance, make sure that the scroll distance value will not
// increased more than the content height and/or less than zero
if ((delta == -1 && current * mean >= -distance) || (delta == 1 && current * mean < 0)) {
current = current + delta;
}
// Move element up or down by updating the `top` value
elem.children[0].style.top = (current * mean) + 'px';
thumb.style.top = 0 - Math.round(trcHeight * (current * mean) / cntHeight) + 'px';
e.preventDefault();
};
if (elem.addEventListener) {
elem.addEventListener("mousewheel", doScroll, false);
elem.addEventListener("DOMMouseScroll", doScroll, false);
} else {
elem.attachEvent("onmousewheel", doScroll);
}
And the markup:
<div id="scroll-area">
<div><!-- CONTENT --></div>
<span class="scrollbar-track"><span class="scrollbar-thumb"></span></span>
</div>
My problem is on mean = 50. When you scroll the container until the bottom of content, the red line that I made in the demo page should stop right at the bottom of the container, not higher than that.
Anyone have an idea for the accurate result?
PS: I also want to add a function that will enable user to scroll the content by dragging the scrollbar thumb. But I think I want to focus on this issue first. Thanks for your help.
DEMO: http://jsfiddle.net/tovic/2B8Ye/

You could have done this much much easier.
Instead of calculating the top property for the container you can set its scrollTop property, and you guess what - you don't have to check if the content moves upper than 0 or lower than height because scrollTop property can not be set to a value smaller than 0 or greater than container's height!
Here's your modified fiddle
Notice that I had to wrap everything with additional <div id="everything">...</div> so the scrollbar won't be scrolled together with the #scroll-area div.
Also I assume using clientHeight instead of offsetHeight for .scroll-content div to include padding in the cntHeight variable.
More info on the scrollTop property you can find in this article.

Related

If bottom of div is visible jquery

Please help me out here, if bottom of div or full div is visible then i want to scroll to down of next div. Here the code i have tried out,
Mathematically,
var top = $("#myDiv").offset().top;
//top = 1863
var divHeight = $("#myDiv").height();
//divHeight = 571
var total = top + divHeight;
//total = 2434
if($('#myDiv').css('height',total).visible(true))
{
alert('hi');
// I need to alert only if the full div is visible not some part of div
}
else
{
//if height of myDiv is larger window height (my screen height 640 pixels)
}
If all this part of html(from top to divHeight) or bottom of page(here total value) is visible then i need to scroll to next div.
Please note :- the code inside if conditional statement is not correct, i think you got some idea from that.
Given element the jQuery object you want to check, element is fully visible if it is shown and all of the 4 sides of its layout box fall within the window viewport.
Caution: the following solution assumes that there are no element with scrollable overflow between element and the document root, otherwise the calculation becomes way more complicated.
function isFullyVisible(element) {
var offset = element.offset();
var scrollTop = $(document).scrollTop();
var scrollLeft = $(document).scrollLeft();
return element.is(":visible") && // shown
offset.top >= scrollTop && // top
offset.left >= scrollLeft && // left
offset.top + element.outerHeight() <= scrollTop + $(window).height() && // bottom
offset.left + element.outerWidth() <= scrollLeft + $(window).width(); // right
}
If you don't care of sides, you can keep only the corresponding sub-expression.

Adjust CSS Opacity With Element's Scroll with jQuery

Hi I want to bind the the CSS opacity of two divs with how much that element is scrolled.
For example say I have two divs:
<div class="red" style="background:red"></div>
<div class="blue" style="background:blue"></div>
As the red div comes into the viewport, its opacity goes from 0 to 100 - depending on the amount scrolled.
Likewise as the blue div comes into viewport its opacity goes from 100 to 0, depending on the amount scrolled.
I found this Jquery/Javascript Opacity animation with scroll -
var fadeStart=100 // 100px scroll or less will equiv to 1 opacity
,fadeUntil=200 // 200px scroll or more will equiv to 0 opacity
,fading = $('#fading')
;
$(window).bind('scroll', function(){
var offset = $(document).scrollTop()
,opacity=0
;
if( offset<=fadeStart ){
opacity=1;
}else if( offset<=fadeUntil ){
opacity=1-offset/fadeUntil;
}
fading.css('opacity',opacity).html(opacity);
});
however the scroll amount is bound the document height, rather than the div itself.
Here is a jsfiddle to work from http://jsfiddle.net/RPmw9/
Thanks in advance.
Depends on when you want it fully opaque or not, but this could be a start:
»»Fiddle«« (Multiple element class version - set individually)
»»Fiddle«« (Single element class version - if only one element per class)
function fader() {
var r = $('.red'), // The .red DIV, as variable so we do not have to look
// it up multiple times.
b = $('.blue'), // Same for blue.
wh = $(window).height(), // Height of window (visible part).
dt = $(document).scrollTop(), // Pixels document is scrolled down.
/* red offset top is a semi static values which say how many pixels it
* is from the top of the document.
* "Red Offset Top" - "Document Scroll Top" gives us how many pixels
* the red DIV is from top of visible window.
* "Window Height" - that value gives us pixels the red DIV is from top
* normalized to start from 0 when top of DIV is at bottom of window.
* */
redView = wh - (r.offset().top - dt),
// Same for blue DIV
blueView = wh - (b.offset().top - dt),
// Variable to save opacity value.
op;
/* If redView is bigger then 0 it means the DIV has top border above bottom
* of window.
*/
if (redView > 0) {
/* Opacity goes from 0 - 1 so we divide 1 by window height and
* multiplies it with pixels red DIV is from bottom.
* In addition we add the height of the red DIV to window height, such
* that we set opacity until it is out of view (Bottom border is at top
* of window, and not only until it has top border at top of window.)
*/
op = 1 / (wh + r.height()) * redView;
/* If value of calulation is less or equal to one, it is in visible
* view and we set the opacity accordingly.
*/
if (op <= 1)
r.css('opacity', op);
}
if (blueView > 0) {
op = 1 - 1 / (wh + b.height()) * blueView;
if (op >= 0)
b.css('opacity', op);
}
// Add this line for a possible help in understanding:
console.log(
'Window Height:', wh,
'Doc Scroll Top', dt,
'Red offset top:', r.offset().top,
'Red offs.top - Doc Scroll Top', r.offset().top - dt,
'View:', wh - (r.offset().top - dt)
);
}
// Attach scroll event to the function fader()
$(document).bind('scroll', fader);
OK. Added some comments. Might not feel it is the best explanation. A better way to understand it is perhaps to have a look at the values so I also added a console.log() line inside the fader() function. Open your console and view the values as you scroll. Fiddle with logging. Also note this performance difference. style is considerably faster.
Version two:
This set full opacity when element has top at top of window, (not bottom of element). Note that we could use the Math.min() in the above function as well, to omit the op variable and if (op <= 1) and if (op >= 0) statement, but not at least a quick benchmark on jsperf revealed the if version to perform slightly better. If you have many elements that you style one should use the if version.
»»Fiddle««
function fader() {
var r = $('.red'),
b = $('.blue'),
wh = $(window).height(),
dt = $(document).scrollTop(),
redView = wh - (r.offset().top - dt),
blueView = wh - (b.offset().top - dt);
if (redView > 0) {
// Math.min() returns the lowest of given values. Here we do not want
// values above 1.
$('.red').css('opacity', Math.min(1 / wh * redView, 1));
}
if (blueView > 0) {
$('.blue').css('opacity', 1 - Math.min(1 / wh * blueView, 1));
}
}
// Event on scroll
$(document).bind('scroll', fader);

Animate {"Top"} how to stop scrolling div on top position being 0 px - Jquery

Trying to create a scrolling div. Wanted to stop (thescrollingdiv) div once it has reached a particular top position and scrolled all the way to the bottom and not overshoot the parent div into infinity scrolling zone. thescrollingdiv does not have any height specified but its parent div does.Thanks.
$('#div a).click(function(e){
e.preventDefault();
$('#thescrollingdiv').stop(true,true).animate({ "top": '-=100px'}, 500)
ScrollTop tells you where you are at. Check the existing top against scrolltop and work the math to set your limits.
var scrollTop = $('#thescrollingdiv').scrollTop();
var newTop = parseFloat($('#thescrollingdiv').css('top')) - 100;
if (scrollTop < 0) {
newTop = 0;
}
$('#thescrollingdiv').stop(true,true).animate({ "top": newTop}, 500)
UPDATE
Something like this.
var topLimit = 0;
var bottomLimit = 800;
var containerTop = parseFloat($('container').css('top'));
var containerBottom = parseFloat($('container').css('height')) + containerTop;
var destination = containerTop - 100;
// compensate for going too far up
destination = (destination < 0) ? 0 : destination;
// compensate for going too far up
destination = (containerBottom > bottomLimit) ? bottomLimit : destination;
// now that you know you are within your custom limits, animate it.
animate(destination);
This is almost pseudo code as I don't know what your code looks like, but it gives you an idea. You have to actually DO THE WORK in setting the limits for your 'newTop', before you call animate in the first place.
You can figure it out. Don't be a lazy programmer, though.

Adjust position of a group of adjacent divs in non-linear fashion

This isn't so much a jQuery question as it is an overall conceptual question.
In my example I can populate a container with divs that have a top value set in a nonlinear fashion.
The top value of each one is calculated based on a formula that takes into account the top position of the one to its left as well as the height of the container (line 33 of fiddle).
//this formula sets the top value for each new child added to the container
//height is 100% of its parent which is 20% of the body
//newOne:last is the most recently added child and will have an initial top value of 10%
parseInt($(this).next().css('top'), 10) / $('#queue').height()) * 75 + (parseInt($('.newOne:last').css('top'), 10) * 2) + '%'
I more of less stumbled upon this by chance and it seems to work 'ok', but if an optimization is obvious to you, please point it out :)
What I'm having trouble coming up with is an elegant formula for how to adjust the children smoothly during a drag event. I'm thinking the top value needs to be adjusted based on some manipulation of the left offset, but after hours of experimenting, I haven't found anything that keeps the original position intact when I start dragging and continues adjusting the values smoothly during my drag. The children should gradually approach a minimum top value of 10% as I drag left (child with left offset of 0 will have a top value of 10%), and gradually move away from that top value back toward their initial position as I drag right.
$('#queue').draggable({
axis: "x",
scroll: false,
drag: function(){
//adjust values of each child
$('.newOne').each(function(){
var percentLeft = $(this).offset().left / $('footer').width() * 100
var thisLeft = parseInt($(this).css('left'), 10) / $(window).width() * 100;
var thisTop = parseInt($(this).css('top'), 10) / $('#queue').height() * 100;
if (percentLeft >= 0){
//top value of each one gradually decreases...
//as it gets closer to an offset value of 0 and minimum top value of 10%
//non-linear attempt but not even close
//$(this).css('top', $(this).css('top', 10 + (thisTop - 10 / thisLeft) + '%'));
//linear step
$(this).css({'top': 8 + (percentLeft/2) + '%'});
}
});
}
});
http://jsfiddle.net/5RRCS/17/
P.S. I know I'm asking a lot here, but hopefully someone is up to the challenge :)
Update:
Stumbled onto exp method and did something like this:
adjustTop = function(offset){
return 100 * (1.0-Math.min(0.98,(0.83 + ( 0.17/ (Math.exp(0.007*offset))) )) ) + '%';
};
$(this).css('top', adjustTop($(this).offset().left) );
Here's a version that I believe does what you are looking for.
The first thing I did was to refactor the top calculation so that both the initialization and the drag handlers would get the same results.
Rather than calculate the positions of the child divs based on their offset to the document, I changed the logic to use position relative to their container.
I also remove z-index as the child divs already being added the parent with the correct stacking order - the left most child is the last element in the container.
Calculating the height of each child depended on whether #queue's current position was to the left or right of its origin.
I also change the iteration logic to behave the same to simplify calculating the current elements starting offset:
$($('.newOne').get().reverse()).each(function (index) {
$(this).css({
'background': 'rgba(255,255,255,.80)',
'top': calcTop($(this), index)
});
});
Code for positioning the child elements:
function calcTop($ele, index) {
var elePositionLeft = $ele.position().left;
var queuePositionLeft = $('#queue').position().left;
var footerWidth = $('footer').width();
var queueHeight = $('#queue').height();
var distanceToTravel = queuePositionLeft < 0 ? elePositionLeft : footerWidth - elePositionLeft;
var percentTraveled = Math.abs(queuePositionLeft) / distanceToTravel;
var thisPercentLeft = (elePositionLeft + queuePositionLeft) / footerWidth;
var queuePercentLeft = queuePositionLeft / footerWidth;
var newTop;
var myStartOffset = (index + 1) * startOffset;
var topTravel = queuePositionLeft < 0 ? -myStartOffset + startOffset : (queueHeight - startOffset);
var linear = false;
if (linear) {
newTop = myStartOffset + (topTravel * percentTraveled);
newTop = newTop > startOffset ? Math.round(newTop) : startOffset;
return newTop;
} else {
if (queuePositionLeft >= 0) {
newTop = myStartOffset + (topTravel * thisPercentLeft * percentTraveled);
newTop = newTop > startOffset ? Math.round(newTop) : startOffset;
} else {
newTop = myStartOffset + (topTravel * (1+thisPercentLeft) * percentTraveled);
newTop = newTop < startOffset ? startOffset : Math.round(newTop);
}
return newTop;
}
}
There was also a minor bug in the reset function - it wasn't setting childCount back to zero:
$('#reset').click(function () {
$('#queue').empty().css('left', 0);
childCount = 0;
});
Demo Fiddle

iScroll Scrolling Past Bottom?

You can easily see the problem on the first page here: http://m.vancouverislandlife.com/
Scroll down (slide up) and allow the content to leave the page, and it doesn't bounce back and is lost forever. However, on pages whose content does overflow the page and is therefore supposed to be scrollable, the scrolling works correctly (see Accomodations > b&b's and scroll down for an example of this).
I noticed that on my computer, the scrolling on the first page is always stuck at -899px. I can't find anybody else who's experienced this problem and no matter what I try, I just can't fix it! Help!
(It's not exactly urgent, however, as the target audience of iPhones and iPod Touches aren't affected by this since they have so little screen room.)
Okay, new problem. To solve the iScroll issue, I just created a custom script. However, it's not working correctly on the actual device. On desktop browsers, it works just fine. On mobile, it occasionally jumps back to the top and won't recognize some touches. This is probably because of the way I cancelled the default event and had to resort to a bit of a hack. How can I fix this? (Yup - simple problem for a +500 bounty. Not bad, huh?)
Here's the script, and the website is at the usual place:
function Scroller(content) {
function range(variable, min, max) {
if(variable < min) return min > max ? max : min;
if(variable > max) return max;
return variable;
}
function getFirstElementChild(element) {
element = element.firstChild;
while(element && element.nodeType !== 1) {
element = element.nextSibling;
}
return element;
}
var isScrolling = false;
var mouseY = 0;
var cScroll = 0;
var momentum = 0;
if("createTouch" in document) {
content.addEventListener('touchstart', function(evt) {
isScrolling = true;
mouseY = evt.pageY;
evt.preventDefault();
}, false);
content.addEventListener('touchmove', function(evt) {
if(isScrolling) {
evt = evt.touches[0];
var dY = evt.pageY - mouseY;
mouseY = evt.pageY;
cScroll += dY;
momentum = range(momentum + dY * Scroller.ACCELERATION, -Scroller.MAX_MOMENTUM, Scroller.MAX_MOMENTUM);
var firstElementChild = getFirstElementChild(content);
content.style.WebkitTransform = 'translateY(' + range(cScroll, -(firstElementChild.scrollHeight - content.offsetHeight), 0).toString() + 'px)';
}
}, false);
window.addEventListener('touchend', function(evt) {
isScrolling = false;
}, false);
} else {
content.addEventListener('mousedown', function(evt) {
isScrolling = true;
mouseY = evt.pageY;
}, false);
content.addEventListener('mousemove', function(evt) {
if(isScrolling) {
var dY = evt.pageY - mouseY;
mouseY = evt.pageY;
cScroll += dY;
momentum = range(momentum + dY * Scroller.ACCELERATION, -Scroller.MAX_MOMENTUM, Scroller.MAX_MOMENTUM);
var firstElementChild = getFirstElementChild(content);
content.style.WebkitTransform = 'translateY(' + range(cScroll, -(firstElementChild.scrollHeight - content.offsetHeight), 0).toString() + 'px)';
}
}, false);
window.addEventListener('mouseup', function(evt) {
isScrolling = false;
}, false);
}
function scrollToTop() {
cScroll = 0;
content.style.WebkitTransform = '';
}
function performAnimations() {
if(!isScrolling) {
var firstElementChild = getFirstElementChild(content);
cScroll = range(cScroll + momentum, -(firstElementChild.scrollHeight - content.offsetHeight), 0);
content.style.WebkitTransform = 'translateY(' + range(cScroll, -(firstElementChild.scrollHeight - content.offsetHeight), 0).toString() + 'px)';
momentum *= Scroller.FRICTION;
}
}
return {
scrollToTop: scrollToTop,
animationId: setInterval(performAnimations, 33)
}
}
Scroller.MAX_MOMENTUM = 100;
Scroller.ACCELERATION = 1;
Scroller.FRICTION = 0.8;
I think Andrew was on the right track with regards to setting the height of the #wrapper div. As he pointed out that,
that.maxScrollY = that.wrapperH - that.scrollerH;
Normally, this would work. But now that you've changed your #content to position: fixed, the wrapper element is no longer "wrapping" your content, thus that.wrapperH has a value of 0, things break.
Disclaimer: I did not go through the entire script so I may be wrong here
When manually setting a height to #wrapper, say 500px, it becomes,
that.maxScrollY = 500 - that.scrollerH;
The folly here is that when there's a lot of content and the window is small, that.scrollerH is relatively close in value to 500, say 700px. The difference of the two would be 200px, so you can only scroll 200 pixels, thus giving the appearance that it is frozen. This boils down to how you set that maxScrollY value.
Solution (for Chrome browser at least):
Since #wrapper effectively contains no content, we cannot use it in the calculations. Now we are left with the only thing that we can reliably get these dimensions from, #content. In this particular case, it appears that using the content element's scrollHeight yield what we want. This is most likely the one that has the expected behavior,
that.maxScrollY = that.scrollerH - that.scroller.scrollHeight;
scrollerH is the offsetHeight, which is roughly the height of what you see in the window. scroller.scrollHeight is the height that's considered scrollable. When the content does not exceed the length of the page, they are roughly equivalent to one another. That means no scroll. When there are a lot of content, the difference of these two values is the amount of scroll you need.
There is still a minor bug, and this looks like it's already there. When you have a lot of content, the last few elements are covered up by the bar when scrolled to the bottom. To fix this, you can set an offset such as,
that.maxScrollY = that.scrollerH - that.scroller.scrollHeight - 75;
The number 75 arbitrary. It's probably best if it's the height of the bar itself with 2 or 3 pixels for a bit of padding. Good luck!
Edit:
I forgot to mention last night, but here are the two sample pages that I used in trying to debug this problem.
Long page
Short page
This may be a CSS issue. In your stylesheet (mobile.css line 22), try removing position:fixed from #content.
That should allow the document to scroll normally (vertical scrollbar on a computer, "slideable" on a mobile browser).
Elements with position:fixed exit the normal flow of the document, their positioning is relative to the browser window. This is probably why you're having issues with scrolling. Fixed positioning is generally for elements which should always remain in the same place, even when the page is scrolled (ie. a notification bar "pinned" at the top of a page).
No definite solution, but more a direction I'd go for:
#wrapper and #content's overflow:hidden paired #content's postion:fixed and seem to be the cause of the issue.
If position: fixed is removed from #content, scrolling is possible but the "blank" divs are wrongly layered (tested in Firefox 5).
Your wrapper div seems to have a height of 0. So all the calculations are negative, setting it's height to the window height will correct the scroll issue. When I manually set the wrappers height via firebug and chromes debug bar the scroll functions as it should.
You #content div seems to have its size change on resize, probably a better idea to have the #wrapper div have its size change and then have #content inherit the size.
[Edit]
You don't believe me so codez, From iscroll-lite.js
refresh: function () {
var that = this,
offset;
that.wrapperW = that.wrapper.clientWidth;
that.wrapperH = that.wrapper.clientHeight;
that.scrollerW = that.scroller.offsetWidth;
that.scrollerH = that.scroller.offsetHeight;
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH;
In your page that translates to,
that.wrapperH = 0;
that.maxScrollY = -that.scrollerH
When a scroll finishes, this code gets called.
var that = this,
resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
resetY = that.y >= 0 || that.maxScrollY > 0 ? 0 : that.y < that.maxScrollY ? that.maxScrollY : that.y;
...
that.scrollTo(resetX, resetY, time || 0);
See that that.maxScrollY > 0 ? ? If maxScrollY is negative then scrolling up will never bounce back.
I ended up just making my own, small script to handle the scrolling:
// A custom scroller
function range(variable, min, max) {
if(variable < min) return min > max ? max : min;
if(variable > max) return max;
return variable;
}
var isScrolling = false;
var mouseY = 0;
var cScroll = 0;
if("createTouch" in document) {
// TODO: Add for mobile browsers
} else {
content.addEventListener('mousedown', function(evt) {
isScrolling = true;
mouseY = evt.pageY;
}, false);
content.addEventListener('mousemove', function(evt) {
if(isScrolling) {
var dY = evt.pageY - mouseY;
mouseY = evt.pageY;
cScroll += dY;
var firstElementChild = content.getElementsByTagName("*")[0];
content.style.WebkitTransform = 'translateY(' + range(cScroll, -(firstElementChild.scrollHeight - content.offsetHeight), 0).toString() + 'px)';
}
}, false);
window.addEventListener('mouseup', function(evt) {
isScrolling = false;
}, false);
}
and modifying a few other parts. It does save a lot of download time, I suppose, also.
I'm still going to accept answers and award the bounty in 5 days, though.
Changed question warrants a new answer. I took a look at the code and I saw that you calculated the momentum on each step of the "move" function. This does not make sense because the momentum is used after the move has ended. What this meant was to capture the mouse position at the beginning, and then calculate the difference at the end. So I added two new variables,
var startTime;
var startY;
Inside the start event (mousedown/touchstart), I added,
startY = evt.pageY;
startTime = evt.timeStamp || Date.now();
Then I have the following for my end handler,
var duration = (evt.timeStamp || Date.now()) - startTime;
if (duration < 300) {
var dY = evt.pageY - startY;
momentum = range(momentum + dY * Scroller.ACCELERATION, -Scroller.MAX_MOMENTUM, Scroller.MAX_MOMENTUM);
} else {
momentum = 0;
}
I also removed the momentum calculation from inside of mousemove/touchmove. Doing this removed the jumping around behavior that I was seeing on my iPhone. I am seeing other unwanted behaviors as well (the whole window "scrolls"), but I'm guessing that you've been working to get rid of those so I didn't attempt.
Good luck. Here's a coded up page that I duplicated for my testing. I also took the liberty to refactor the code for this section to remove some duplicated code. It's under mobile3.js if you want to look at it.

Categories

Resources