Animate element based on scroll position inside absolute div with overflow: scroll - javascript

I'm trying to animate an element based on the scroll position inside a div with the properties position: absolute and overflow: scroll. The code I've got to so far is basing the animation based on the position on the page position, and changing the opacity. I want to change the property filter: blur(value); Below is the code (opacity, not div based scroll) as it exists now:
var header = $('div.modal-container figure.still');
var range = 200;
$(window).on('scroll', function() {
var scrollTop = $(this).scrollTop(),
height = header.outerHeight(),
offset = height / 2,
calc = 1 - (scrollTop - offset + range) / range;
header.css({
'opacity': calc
});
if (calc > '1') {
header.css({
'opacity': 1
});
} else if (calc < '0') {
header.css({
'opacity': 0
});
}
});
Any help on how I can accomplish this?

If you have in calc variable radius of blur in pixels, try something like this:
header.css({
'filter': `blur(${calc}px)`
});
if (calc < 0) {
header.css({
'filter': 'none'
});
}

Related

Stop animation at certain position on page [jQuery]

I have a div that moves across the page on a keydown event listener. I'm trying to find a way to make it stop after either a certain number of keydowns (calculated by step * clicks > screen size) or when the animated div reaches the end of the screen, which I guess would need to be responsive to screen size.
Currently the animate continues to fire on keydown and the div will scroll off out of view.
An example of this is the second demo on this page: http://api.jquery.com/animate/
You can click left or right until the block moves out of view. How would I contain it to it's uh, container?
here's my jsfiddle: https://jsfiddle.net/vidro3/1a8tnuer/
var count1 = 0;
var count2 = 0;
// 1. Get two divs to move on different key presses;
$(function(){
$(document).keydown(function(e){
switch (e.which){
case 39: //lright arrow key
count2++;
$('.box2').animate({
left: '+=50'
});
break;
case 90: //z key
count1++;
$('.box1').animate({
left: '+=50'
});
break;
}
});
});
// 2. Get one div to move on button click;
$(function(){
$( '#start' ).click(function() {
alert('Chug that Duff!');
var rabbit = $(".rabbit");
rabbit.animate({left: '+=100%'}, 'slow');
});
});
$(function(){
var winPos = $('#background').width();
if (winPos/50 > count1)
alert('Homer Wins!');
else if (winPos/50 > count2)
alert('Barney Wins!');
});
Just add a conditional to the animation:
var maxLeft = $(window).width() - $('.box1').width();
// If the box's x-position is less than the max allowed, then animate
if ($('.box1').position().left < maxLeft) {
$('.box1').animate({
left: '+=50'
});
}
The value (window width - box width) is the point at which the box is at the end of the screen. Note that your step size may take the box past the end of the screen depending on the current window size (it's probably not divisible by 50, for example), so you may want something like this instead:
var stepSize = 50;
var maxLeft = $(window).width() - $('.box1').width();
// If the box's x-position is less than the max allowed, then animate
if ($('.box1').position().left < maxLeft) {
var diff = maxLeft - $('.box1').position().left;
// If the next step would take the box partially off the screen
if (diff < stepSize) {
$('.box1').animate({
left: '+=' + diff
});
} else {
$('.box1').animate({
left: '+=' + stepSize
});
}
}
Edit: here's a shorter version using the ternary operator:
var stepSize = 50;
var maxLeft = $(window).width() - $('.box1').width();
// If the box's x-position is less than the max allowed, then animate
if ($('.box1').position().left < maxLeft) {
var diff = maxLeft - $('.box1').position().left;
$('.box1').animate({
left: '+=' + (diff < stepSize ? diff : stepSize)
});
}

How to add a jQuery scrollTop offset?

I'm trying to get the div to snap to the center of the viewport, right now it just snaps to the top. I was trying to put an offset of 50% but can only get it in px's.
EDIT
I added a new fiddle where I tried to include $(window).scrollTop() / 2)
http://jsfiddle.net/kZY9R/84/
$("#item").offset().top - 100
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if ($(value).offset().top > $(window).scrollTop()) {
animating = true;
$(body).stop().animate( { scrollTop: $(value).offset().top }, 1000,'swing');
setTimeout(function() { animating = false; }, 2000);
return false;
}
});
}, 50));
}
});
I found this:
$('html, body').animate({scrollTop: $('#your-id').offset().top -100 }, 'slow');
Source: Run ScrollTop with offset of element by ID
Here's the trick to keep your viewport centralized on a particular div.
Prerequisites
You need to take into account the following three criteria to be able to centralize the viewport on a given item:
height of the last item that appeared on the viewport.
The distance of the last item from the top of the page, i.e. the offset().top of the item.
The height value of the viewport (i.e the window object).
Calculating Vertical Position of the Item
The required scrollTop value for the window can be calculated as in the following:
var scrollValue = itemOffset // offset of the item from the top of the page
- .5 * windowHeight // half the height of the window
+ .5 * itemHeight; // half the height of the item
You are basically, moving the top of your viewport to the item under view's top offset initially. This, as you've already experienced, snaps the item to the top of the window.
The real magic part comes when you subtract half of the window's height to go halfway along it vertically, and then shifting your view back down by adding half the item's height. This makes the item appear vertically centralized with regards to the viewport.
Note:
To be able to query the last item that appeared on the viewport, you have to iterate over all of the elements that have a top offset value (i.e. offset().top) less than or equal to that of the window's scrollTop value:
$.each($('.item'), function(i, value) {
if ($(viewport).scrollTop() >= $(this).offset().top) {
lastItemInView = $(this);
}
});
With the above, the lastItemInView variable will always end up with the last element visible in the window.
Demo
Not sure if you figured this out yet or not but I took some code from this answer (How to tell if a DOM element is visible in the current viewport?) that shows how to tell if an element is visible in the view port.
Using that I modified your code to loop through each item and find the first visible one in the viewport and then center that one also factoring in the margin-top you have. Let me know if this helps!
Fiddle: http://jsfiddle.net/kZY9R/86/
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if (elementInViewport(value)) {
animating = true;
var margin = parseInt($(value).css('margin-top'));
$('html,body').animate({
scrollTop: $(value).offset().top - ($(window).height() + margin - $(value).outerHeight(true)) / 2
}, 200);
setTimeout(function() {
animating = false;
}, 2000);
return false;
}
});
}, 50));
}
});
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while (el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}

opacity on scroll with jquery

I'm trying make the opacity of my div gradually increasing, as will moving the scroll, like this
$(document).ready(function() {
$(document).scroll(function(e) {
opacidade();
});
var element = $('#element');
var elementHeight = element.outerHeight();
function opacidade() {
var opacityPercent = window.scrollY / 100;
if (scrollPercent <= 1) {
element.css('opacity', opacityPercent);
}
}
});
is working but the opacity is uping very fast i find example decrease opacity but no uping upacity if in my rule css my div is declared opacity 0 any knwo how should be
Altered:
jsFiddle
$(document).ready(function() {
$(document).scroll(function(e){
opacidade();
});
var element = $('#element');
var elementHeight = element.outerHeight();
function opacidade(){
var opacityPercent = window.scrollY / $(document).height();
console.log(window.scrollY, opacityPercent);
element.css('opacity', opacityPercent);
}
});
The scrollY is a pixel value, so unless you limit your possible scroll range [0 - 100], there's no reason to divide it by 100.
So what you need is divide the scroll by the total document's height (or whatever it's parent that contains it and display a scrollbar)

Get the visible height of a div with jQuery

I need to retrieve the visible height of a div within a scrollable area. I consider myself pretty decent with jQuery, but this is completely throwing me off.
Let's say I've got a red div within a black wrapper:
In the graphic above, the jQuery function would return 248, the visible portion of the div.
Once the user scrolls past the top of the div, as in the above graphic, it would report 296.
Now, once the user has scrolled past the div, it would again report 248.
Obviously my numbers aren't going to be as consistent and clear as they are in this demo, or I'd just hard code for those numbers.
I have a bit of a theory:
Get the height of the window
Get the height of the div
Get the initial offset of the div from the top of the window
Get the offset as the user scrolls.
If the offset is positive, it means the top of the div is still visible.
if it's negative, the top of the div has been eclipsed by the window. At this point, the div could either be taking up the whole height of the window, or the bottom of the div could be showing
If the bottom of the div is showing, figure out the gap between it and the bottom of the window.
It seems pretty simple, but I just can't wrap my head around it. I'll take another crack tomorrow morning; I just figured some of you geniuses might be able to help.
Thanks!
UPDATE: I figured this out on my own, but looks like one of the answers below is more elegant, so I'll be using that instead. For the curious, here's what I came up with:
$(document).ready(function() {
var windowHeight = $(window).height();
var overviewHeight = $("#overview").height();
var overviewStaticTop = $("#overview").offset().top;
var overviewScrollTop = overviewStaticTop - $(window).scrollTop();
var overviewStaticBottom = overviewStaticTop + $("#overview").height();
var overviewScrollBottom = windowHeight - (overviewStaticBottom - $(window).scrollTop());
var visibleArea;
if ((overviewHeight + overviewScrollTop) < windowHeight) {
// alert("bottom is showing!");
visibleArea = windowHeight - overviewScrollBottom;
// alert(visibleArea);
} else {
if (overviewScrollTop < 0) {
// alert("is full height");
visibleArea = windowHeight;
// alert(visibleArea);
} else {
// alert("top is showing");
visibleArea = windowHeight - overviewScrollTop;
// alert(visibleArea);
}
}
});
Calculate the amount of px an element (height) is in viewport
Fiddle demo
This tiny function will return the amount of px an element is visible in the (vertical) Viewport:
function inViewport($el) {
var elH = $el.outerHeight(),
H = $(window).height(),
r = $el[0].getBoundingClientRect(), t=r.top, b=r.bottom;
return Math.max(0, t>0? Math.min(elH, H-t) : Math.min(b, H));
}
Use like:
$(window).on("scroll resize", function(){
console.log( inViewport($('#elementID')) ); // n px in viewport
});
that's it.
jQuery .inViewport() Plugin
jsFiddle demo
from the above you can extract the logic and create a plugin like this one:
/**
* inViewport jQuery plugin by Roko C.B.
* http://stackoverflow.com/a/26831113/383904
* Returns a callback function with an argument holding
* the current amount of px an element is visible in viewport
* (The min returned value is 0 (element outside of viewport)
*/
;(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i,el) {
function visPx(){
var elH = $(el).outerHeight(),
H = $(win).height(),
r = el.getBoundingClientRect(), t=r.top, b=r.bottom;
return cb.call(el, Math.max(0, t>0? Math.min(elH, H-t) : Math.min(b, H)));
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
Use like:
$("selector").inViewport(function(px) {
console.log( px ); // `px` represents the amount of visible height
if(px > 0) {
// do this if element enters the viewport // px > 0
}else{
// do that if element exits the viewport // px = 0
}
}); // Here you can chain other jQuery methods to your selector
your selectors will dynamically listen to window scroll and resize but also return the initial value on DOM ready trough the first callback function argument px.
Here is a quick and dirty concept. It basically compares the offset().top of the element to the top of the window, and the offset().top + height() to the bottom of the window:
function getVisible() {
var $el = $('#foo'),
scrollTop = $(this).scrollTop(),
scrollBot = scrollTop + $(this).height(),
elTop = $el.offset().top,
elBottom = elTop + $el.outerHeight(),
visibleTop = elTop < scrollTop ? scrollTop : elTop,
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
$('#notification').text(`Visible height of div: ${visibleBottom - visibleTop}px`);
}
$(window).on('scroll resize', getVisible).trigger('scroll');
html,
body {
margin: 100px 0;
}
#foo {
height: 1000px;
background-color: #C00;
width: 200px;
margin: 0 auto;
}
#notification {
position: fixed;
top: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="foo"></div>
<div id="notification"></div>
The logic can be made more succinct if necessary, I've just declared separate variables for this example to make the calculation as clear as I can.
Here is a version of Rory's approach above, except written to function as a jQuery plugin. It may have more general applicability in that format. Great answer, Rory - thanks!
$.fn.visibleHeight = function() {
var elBottom, elTop, scrollBot, scrollTop, visibleBottom, visibleTop;
scrollTop = $(window).scrollTop();
scrollBot = scrollTop + $(window).height();
elTop = this.offset().top;
elBottom = elTop + this.outerHeight();
visibleTop = elTop < scrollTop ? scrollTop : elTop;
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
return visibleBottom - visibleTop
}
Can be called with the following:
$("#myDiv").visibleHeight();
jsFiddle
Here is the improved code for jquery function visibleHeight: $("#myDiv").visibleHeight();
$.fn.visibleHeight = function() {
var elBottom, elTop, scrollBot, scrollTop, visibleBottom, visibleTop, height;
scrollTop = $(window).scrollTop();
scrollBot = scrollTop + $(window).height();
elTop = this.offset().top;
elBottom = elTop + this.outerHeight();
visibleTop = elTop < scrollTop ? scrollTop : elTop;
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
height = visibleBottom - visibleTop;
return height > 0 ? height : 0;
}

Lightweight scrollUp function - jQuery

Trying to make simple jQuery function to create a scrollToTop button that fades in as you scroll down.
$(document).ready(function() {
var start = 300;
var duration = 200;
var scrolled;
$('.scrollUp').css('opacity', '0.0');
$(window).scroll(function(){
var opacity = (scrolled - start) / duration;
scrolled = $(window).scrollTop();
if (0 < opacity < 1) {
$('.scrollUp').css('display', 'block').css('opacity', opacity);
} else if (1 < opacity) {
$('.scrollUp').css('display', 'block').css('opacity', '1.0');
} else {
$('.scrollUp').css('display', 'none').css('opacity', '0.0');
}
});
$('.scrollUp').click(function(){
$('html, body').animate({
scrollTop: 0
}, 500);
});
});
See it in action here: http://jsfiddle.net/JamesKyle/fBvGH/
This works, tested in jsfiddle:
$(document).ready(function() {
var start = 300;
var duration = 200;
var scrolled;
$('.scrollUp').css('opacity', '0.0');
$(window).scroll(function(){
var opacity = (scrolled - start) / duration;
scrolled = $(window).scrollTop();
if (0 < opacity < 1) {
$('.scrollUp').css('display', 'block').css('opacity', opacity);
} else if (1 < opacity) {
$('.scrollUp').css('display', 'block').css('opacity', '1.0');
} else {
$('.scrollUp').css('display', 'none').css('opacity', '0.0');
}
});
$('.scrollUp').click(function(){
$('html,body').animate({
scrollTop: 0
}, 500);
});
});
Update:
And here's a working example with the opacity animation.
Looks like this guy was looking for the same equation.
Better to use some math in situation's like this:
scrolled = $(window).scrollTop();
height = $('body').height();
height = Math.ceil((scrolled / height) * 100);
height = height / 100;
Second Update
Ok, you want it to start appearing after the dark blue section. Ok, so what you need to do is exclude that portion of the top before the gradient. You can do that by making an if clause that checks if the scrollTop value has hit the top part of the light blue gradient; around 300px from the top of the document. Then instead of using the body height in the above equation, use the total height of the gradient section; about 210px. This value will replace the var height in the jQuery above. Let me know if you have issues implementing this. Didn't notice you're comment on the above answer.
scrollTop is not a window property, so just change you code slightly:
$(window).animate({scrollTop : 0},500);
to
$('html, body').animate({scrollTop : 0},500);
here's the updated jsfiddle: http://jsfiddle.net/fBvGH/13/

Categories