Set div width based on scroll position - javascript

The code:
http://codepen.io/anon/pen/EjrpMM
So, i'm working on an interesting problem. I am working with a 2000px HTML document, that has a modal placed ontop of it.
The width of the div lightbox is 80%, and it's sitting positioned fixed.
The goal is, when scrolling down the page, to control the width of the div based on the scroll position. At the bottom of the page, it's only a third in size.
I've had trouble figuring out the proper equation or formula for this, and was seeking help.
Currently, I've been trying to look at the window.pageYOffset, to add 2.5% to the div while increasing, and minus 2.5% when scrolling back up, to bring it back to it's 80% width.
However, something isn't working right. I was seeing if the community had any ideas to help solve the problem.
I'm not using any frameworks for this.
Here's my javascript:
var lightBox = document.getElementById('lightBox'),
count = 80,
num = window.pageYOffset;
document.addEventListener('scroll', function(e) {
var offset = window.pageYOffset;
num >= offset ? count += 2.5 : count -= 2.5;
num = offset;
lightBox.style.width = count + '%';
});
View the code here, in this codepen
http://codepen.io/anon/pen/EjrpMM
Thank you!

You just have to change
+= 2.5 and -=2.5 to += 0.7 and -= 0.7
When I checked your code I did this and it worked.

Scroll event fired once on scroll independently on how much you've scrolled. E.g. if you've scrolled 1px scrollbar, or scrolled 100px using mousewheel scroll event will be fired once.
So if you need stable results you will need to calculate your div width depending on scroll position (window.pageYOffset).
Check this codepen fork. I've assumed that in the end of page div width should be 50%.
Core part is:
var lightBox = document.getElementById('lightBox');
var upperBound = 80;
var lowerBound = 50;
var tickValue = (upperBound - lowerBound) / window.innerHeight;
document.addEventListener('scroll', function(e) {
var offset = window.pageYOffset;
var count = upperBound - offset * tickValue;
lightBox.style.width = count + '%';
});
Important note: for crossbrowser way to get innerHeight you can check this answer

This is a simple equation. Let f : scroll |-> f(scroll) be the function that gives you the width of your div. You want f(0) = 0.8, f(2000)= 1/3.
Let's say you want the progression to be linear so f(scroll) = a*scroll + b, you can easily deduce that b = 0.8 and a = (1/3 - 0.8)/2000 = -0.000233. Now for any scroll value, you can find the width of your div.
Now you can change the values when you want, f(scroll) = (minWidth-maxWidth)/pageLength * scroll + maxWidth.

Related

How to calculate remaining height even when overflow scroll stops. [JQUERY]

I created a custom scrollbar behavior of a div that goes down based on calculated; height of parent and current position scrollTop.
However, when the content reaches the end, the div stays in the middle and does not go beyond the top: 100% (actually it's 85 to be precise) How can I calculate that the div actually goes to the bottom?
$('.carousel-items').scroll(function() {
var currY = $(this).scrollTop();
console.log(currY);
var postHeight = $(this).height();
var scrollHeight = $('.carousel-item').height();
var scrollPercent = (currY / (scrollHeight - postHeight)) * 100;
scrollPercent = Math.abs(scrollPercent);
$('.test').css('top', scrollPercent +"%" );
});
I tried multiplying the sum by 1000 instead of 100, but the items in the content are dynamically added. I am now in a test environment (experimenting with 4 items) but when the project finishes the items in it could be like 20..
As you can see in the image, the scrollbar is reaches the end but the blue T div stays at the middle.
enter image description here

Issue calculating table scrollbar location

So I have a script that adds a slight shadow to table edge where you can scroll, depending on the location of the scrollbar, but it sometimes doesn't work.
This is one part of it:
$('table').on('scrollstart scrollstop', function(){
if($(this).parent().hasClass('table-wrap')){
var elem = $(this),
elemBody = elem.find('tbody'),
elemParent = elem.parent('.table-wrap');
var scrolled = (elemBody.outerWidth() - elemParent.outerWidth() - elem.scrollLeft());
if(scrolled === 0){
elemParent.addClass('left_active');
elemParent.removeClass('right_active');
} else if(elem.scrollLeft() === 0) {
elemParent.removeClass('left_active');
elemParent.addClass('right_active');
} else {
elemParent.addClass('left_active');
elemParent.addClass('right_active');
}
}
});
This part sometimes I have to add "+1" to "elem.scrollLeft() --here---); to make it work.
var scrolled = (elemBody.outerWidth() - elemParent.outerWidth() -
elem.scrollLeft());
But then I noticed, some tables it helps and on others, it stops working. Meaning when I scroll to right the 'right_active' class will not disappear.
Any suggestions?
Have you tried including scrollbar width in your calculation for var scrolled?
var scrolled = (elemBody.outerWidth() - elemParent.outerWidth() - elem.scrollLeft());
I think you are on the right track but the width is probably not precise since .outerWidth() doesn't include scrollbar width. Hence, the maximum scroll width is always greater than the actual element width.

Div to follow scrollbar proportionally on a page

I'm now struggling on a sticky element that should scroll proportionally on a page. From top to the footer despite the page's height. So it's actually stick to the top of the scrollbar in the beginning and then to the bottom at the end. Or it just follows the scroll wheel.
Is there any chance to do it with jQuery ?
Below is the starting code with usual "sticky" div.
$(window).scroll(function(){
$("#sticky")
.animate({"marginTop":($(window).scrollTop())+"px"}, "fast");});
https://jsfiddle.net/flakessp/cxr78xc8/
Do you mean something like this?
$(window).scroll(function() {
// calculate the percentage the user has scrolled down the page
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
// get the height of the sticky element
var stickyHeight = $('.sticky').height();
// calculate the margin top of the sticky element
var marginTop = (($(window).height() - stickyHeight) / 100) * scrollPercent;
// set margin top of sticky element
$('.sticky').css('marginTop', marginTop);
});
Fiddle
So, this one was a little tricky, but here it is:
JSFiddle example
Basically, we're using a couple things here:
Scroll direction detection with this section:
var lastScrollPos = 0,
...
lastScrollPos < $window.scrollTop()
Then, you forgot to factor in things like document and window height. scrollTop does exactly what it says and only gives you the number from the top of the viewport to the top of the document. So we add in the visible height as well with $(window).height().
Then it's just a matter of whether we factor in the height of the element too (hence the ternary operator adding 0 or $('#sticky').height() depending on our scroll direction detection from the earlier section.
Anyhow, here's the full JS:
var lastScrollPos = 0,
$window = $(window),
$document = $(document),
$sticky = $('#sticky');
$(window).scroll(function(){
$sticky
.animate({"top":((($window.scrollTop() + (lastScrollPos < $window.scrollTop() ? $window.height() - $sticky.height() : 0))/$document.height()) * 100)+"%"}, "fast");
});

get percentage scrolled of an element with jquery

I'm trying to get an div to animate 0% - 100% relative to the percentage scrolled of an element.
Now I've set up a few variables, but I'm having trouble trying to calculate the height of one by percentage.
We can set the starting width quite easily and detect the scroll easily enough too, as can we get the height of the element that'll trigger the animation, I just can't get it as a percentage.
If I can figure out how to return the percent of conheight scrolled then this should be easy.
$(window).scroll(function() {
// calculate the percentage the user has scrolled down the page
var scrollPercent = ($(window).scrollTop() / $(document).height()) * 100;
$('.bar-long').css('width', scrollPercent +"%" );
});
Here's a jsfiddle, http://jsfiddle.net/SnJXQ/
This is animating bar-long based on the percent scrolled of the body element.
Animates from 0% - 100% (well, it doesn't really, but I can't figure out why).
What I'd like to do is get scroll percent of the .post div, then animate bar-long relative to that.
ie. Scrolled 10% of .post, .bar-long is 10% width, scrolled 70% of .post, .bar-long is 70% width.
Demo
Your problem is the same as How to get horizontal scrolling percentage of an HTML element in JavaScript?, but vertically.
Then, to get the vertically scrolled percentage, use
/* JS */ var scrollPercentage = 100 * containeR.scrollTop / (containeR.scrollHeight-containeR.clientHeight);
/*jQuery*/ var scrollPercent = 100 * $(containeR).scrollTop() / ($(containeD).height() - $(containeR).height());
In your case, containeR = window; containeD = document:
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
Ok I see what you are trying to achieve....in fact I just did something very similar. Most solutions I found out there also were only for full page examples with window or document properties. Instead I needed this in a specific div which in my case was actually used to update the horizontal position of another div.
First, you are going to want the scroll event attached to your $('.post')
Next, the height of the $('.content') is going to equal your actual Scroll Height
Lastly, apply your percentage formula : (Y / (scrollHeight - postHeight)) * 100 = scrollPercent
So instead of using document or window attributes your code should be as follows:
$('.post').scroll(function() {
var currY = $(this).scrollTop();
var postHeight = $(this).height();
var scrollHeight = $('.content').height();
var scrollPercent = (currY / (scrollHeight - postHeight)) * 100;
});
You can find the fiddle here: JS Fiddle For Div Scroll Percentage
The current project where I have implemented this is located here: Vertical Scroll Drives Horizontal Position
I hope this solves your problem :)
Let's say you want to keep track of the scroll of some document found in some IFrame in your page.
object.addEventListener("scroll", documentEventListener, false);
Then your event listener should look like this:
function documentEventListener(){
var currentDocument = this;
var docsWindow = $(currentDocument.defaultView); // This is the window holding the document
var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window
var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport
var docHeight = $(currentDocument).height(); // This is the full document height.
var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
}

how do i get the x and y position directly under the left bottom side of the input rectangle?

I'm thinking of implementing a custom auto-complete feature so basically my idea now is that i will make an abs positioned div and give it the position here:
(image) http://i.stack.imgur.com/3c5BH.gif
So my question is with a variable referencing the textbox, how do i get the x and y position directly under the left bottom side of the input rectangle?
My script must work in latest versions of IE / FF / Safari / Opera / Chrome
I know i can use a library to do it, but no i'm interested in learning how do they do it (or maybe better ways)?
This question is a lot more complicated than it seems and involves getting the position of the element relative to the document. The code to do so can be pulled from the jquery source (http://code.jquery.com/jquery-1.6.1.js -- search for "jQuery.fn.offset")
in jQuery:
var node = $('#textbox'),
pos = box.offset(); // the complicated piece I'm using jQuery for
node.top += node.height(); // node.offsetHeight without jQuery
node.left += node.width(); // node.offsetWidth without jQuery
The answer can be extremely simplified if you don't care about FF2 or Safari3:
var box = document.getElementById('yourTextBox').getBoundingClientRect(),
left = box.left,
bottom = box.bottom;
x = x offset
y = y offset - ( textbox height +
padding-top + padding-bottom )
Good comments! For my scenario, there is always an offset parent (which is why I use position - http://api.jquery.com/position/). In hopes that it might help someone else wanting a quick fix, here's the code:
// I have a parent item (item) and a div (detail)
// that pops up at the bottom left corner of the parent:
var jItem = $(item);
var pos = jItem.position();
var marginTop = parseInt(jItem.css('margin-top'));
if (isNaN(marginTop)) {
marginTop = 0;
}
$(detail).css("top", pos.top + jItem.outerHeight() + marginTop)
.css("left", pos.left);
$(detail).show();
Just give the box a defined width and height. Then, get its top and left property and add it with the width and height. Simple. I am gonna give you Pseodocode.
<STYLE>
object{width: 100px; height: 20px;}
</STYLE>
<SCRIPT>
x = object.left;
y = object.top;
x = x + object.width;
y = y + object.height;
</SCRIPT>

Categories

Resources