Not sure what the method is or how its achieved. But I'm interested in knowing about it to possibly use it in an upcoming project. What I am referring to is when a block element is at a particular X/Y axis it seems it stops acting as though it were a fixed position element otherwise the element acts as a fixed position element.
I most commonly see this with navigation, where the header and footer are large and the element will stop acting as a fixed element when it reaches the bottom of the header or top of the footer
You can do something like this,
$(window).scroll(function(){
if ($(this).scrollTop() > 250){
$('#top').css('position','fixed');
}
else{
$('#top').css('position','static');
}
});
A better approach would be,
$(window).scroll(function(){
var top = $('#top');
if ($(this).scrollTop() > 250){
if(top.css('position') !== 'fixed'){
top.css('position','fixed');
}
}
else{
if(top.css('position') !== 'static'){
top.css('position','static');
}
}
});
There are plugins that will do this for you; this is one I've used before: link with relative success. Has great examples, too.
But if you want to do it yourself, it's not too difficult. The concept is slightly convoluted; if you change something's position to fixed, then it will not take up space, as it would if it was static.
When I came across this issue, I created a second item in the same place (or not, depending where you want it to appear), which is invisible. Then you implement a load/scroll event that checks if the window's scrollTop is greater than the top coordinate of the non-fixed object. If it is, show the fixed object.
Something like this:
$("#yourObject").each(function() { // The ID should be the FIXED object.
var $me = $(this);
var $heightRival = $("#anotherObject"); // This ID should be the non-fixed object.
$me.hide(); // Hide your fixed div.
$(window).bind("load scroll",function() {
var offset = $heightRival.offset(); // Get the document offset of the base object.
var height = $heightRival.outerHeight(); // Get the height of the base object.
if ($(window).scrollTop() > offset.top+height)
$target.show(); // Can be a fade in, slide in, whatever.
else
$target.hide(); // Can be a fade out, etc.
});
});
This is just a rudimentary code but it should set you on the right track.
Take a look at this plugin, or the others like it: http://www.orangecoat.com/stickyscroll
Related
I need to know if the end of a div element is currently visible in the users' browser.
I tried something I saw on the web, but scrollTop() always gave me zero in my Browser. I read something about an issue in Chrome, but I didn't understand quite well.
jQuery(
function($) {
$('#flux').bind('scroll', function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
alert('end reached');
}
})
}
);
My idea is the following:
1- User loads page and sees a Bar (sticky div at bottom visible page) with some information.
2- After scrolling a bit, and reaching the end of a div element, this bar will position there, after the div. This is the bar's original position
I wasn't really able to know when I was at the end of the div element. Eventually I found this code:
if ($(window).scrollTop() >= $('#block-homepagegrid').offset().top + $('#block-homepagegrid').outerHeight() - window.innerHeight) {
$('.hero-special-message').removeClass('hero-special-messege-scrolling');
} else {
$('.hero-special-message').addClass('hero-special-messege-scrolling');
}
});
I see that it's working, but I'm having a bit of trouble understanding what it does.
I know the following:
1. $(window).scrollTop();
this gives me the amount of pixels the user has scrolled, pretty self explanatory.
2. $('#block-homepagegrid').offset().top;
I THINK this is the distance between the start of the page and the start of the div. I know it's the current coordinates, but what is top exactly here?
3. $('#block-homepagegrid').outerHeight();
this gives the height of the element, I know there are 3, like
height(), innerHeight() and outerHeight(), if you want to take into
account border, margin, padding, which is the better to use?
4. window.innerHeight;
I understand this is what the user sees, but I'm having troubles understanding why does it matter for my situation.
Thanks!
You may be interested in the native JavaScript IntersectionObserver API. It automatically figures out what percentage of a given element is visible in the window and triggers callbacks based on that. So then you can do this:
function visibleHandler(entries) {
if (entries[0].intersectionRatio >= 1.0) {
// The whole element is visible!
} else {
// Part of it is scrolled offscreen!
}
}
const observer = new IntersectionObserver(visibleHandler, {threshold: 1.0});
observer.observe(document.getElementById('flux'));
Now, whenever the element with ID flux is 100% in view, it will trigger the visibleHandler. It will also trigger again if it's scrolled back out of view; that's why the function checks the ratio of visibility to see if it just hit 100% or just got reduced from 100%. You could be more fancy and use the observer entry's insersectionRect, which gives you the rectangle containing the visible portion of the element, and use that to determine top/bottom visibility.
I am trying to get the height of my navigation and apply it to a margin-top so I can offset my banner. My navigation is fixed so I'm trying to compensate for that so my banner isn't hidden underneath.
// Offset Banner to Height of Navigation
function bannerOffset() {
var bannerTop = $('.x-navbar').height();
$('#banner-carousel').css('margin-top', bannerTop);
}
This, I thought would do it, but it doesn't reflect anything at all in the front-end.
UPDATE
$(document).ready(function() {
var bannerTop = $('.x-navbar').outerHeight();
$('.x-main').css('margin-top', bannerTop);
$(window).scroll(function() {
var bannerTopScroll = $('.x-navbar.scroll').outerHeight();
if ($(document).scrollTop() > 1) {
$('.x-main').css('margin-top', bannerTopScroll);
}
});
});
So I thought I had this, but on load, the margin-top of .x-main is 245px. When I scroll it becomes 85px. I can see the numbers go down to that. The issue is when I scroll back up to the top the value doesn't go back to 245px. It's not very consistent, but I often get 144px. I should add that, and this is probably why, I have another function that changes the height of my .x-navbar when .scroll is added to it.
$(window).scroll(function() {
if ($(document).scrollTop() > 1) {
$('.x-navbar').addClass('scroll');
} else {
$('.x-navbar').removeClass('scroll');
}
});
So I am not sure how to make this all smooth and working properly. If I reload the page the .x-mainis back to 245px. When I scroll back to the top it's not calculating properly.
Your code works. Maybe you want to use $.outerHeight() instead, your selectors are wrong, or you're experiencing margin collapsing.
It's worth noting that $.height() returns an integer value, so in your $.css() line, you should change bannerTop to bannerTop + 'px' so that the CSS has a unit and not just a number... but it looks like jQuery is doing that automagically for me here. You might try it and see.
var bannerTop = $('.x-navbar').height();
$('#banner-carousel').css('margin-top', bannerTop);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="x-navbar">x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br></div>
<div id="banner-carousel">banner carousel</div>
I am looking to create a scrolling effect similar to that shown here: http://www.seaham-hall.co.uk/
However I am unable to achieve the desired effect, and inspecting the sites code gives me no hints. Quite difficult to google for as it is also quite difficult to describe. The closest I can get to finding a solution is this JSFiddle:
http://jsfiddle.net/xtyus/1/
(function($){
/* Store the original positions */
var d1 = $('.one');
var d1orgtop = d1.position().top;
var d2 = $('.two');
var d2orgtop = d2.position().top;
var d3 = $('.three');
var d3orgtop = d3.position().top;
var d4 = $('.four');
var d4orgtop = d4.position().top;
/* respond to the scroll event */
$(window).scroll(function(){
/* get the current scroll position */
var st = $(window).scrollTop();
/* change classes based on section positions */
if (st >= d1orgtop) {
d1.addClass('latched');
} else {
d1.removeClass('latched');
}
if (st >= d2orgtop) {
d2.addClass('latched');
} else {
d2.removeClass('latched');
}
if (st >= d3orgtop) {
d3.addClass('latched');
} else {
d3.removeClass('latched');
}
if (st >= d4orgtop) {
d4.addClass('latched');
} else {
d4.removeClass('latched');
}
});
})(window.jQuery);
However I am not sure that is going in the right direction, this pulls images up and covers the previous image, but notice on the Seaham Hall site the images don't appear to move up at all, they are stationary and become revealed as you scroll.
How do I recreate this effect? My initial thought was to have the first image shrink as you scroll from 1000px down to 0px, and the second image grow to 1000px, and as you continue to scroll this image then shrinks and the third grows, and so on. However this means that after the first image all the other images have a starting size of 0px and there would technically be no scrolling on the page to begin with, so that is an issue.
My second thought is that perhaps the second image is fixed to the page, the first image slides up revealing the second as you scroll, the second image would not appear to move. Once the first image has gone off the top of the page the second image is detached from the page and allowed to move up with scrolling, while the third image is attached and revealed as the second moves up, this would give the exact effect seen in the Seaham website but I have no clue of it is the correct answer.
If anyone can point me to tutorials or a JSFiddle with a basic concept I can probably figure it out from there. Just stumped what direction to approach this from.
That's a nice effect. Here's one way to do it.
Put each image in a fixed position div, which takes up the entire viewport (initially) and has overflow:hidden.
Set each div's z-index to be higher than the next div's.
As the window scrolls, adjust the height of the divs as a function of the window height times the div's position (index) in the DOM, minus the window's scrollTop:
$(window).scroll(function() {
$('.D').each(function(index) {
$(this).css({
height: $(window).height()*(index+1) - $(window).scrollTop()
});
});
});
Additional content will need a higher z-index than the image divs. And note that z-index works with positioned elements only.
Fiddle
Your desired effect isn't technically a parallax background, but it's close enough that parallax jQuery frameworks should work for you.
I would suggest you research jQuery Parallax plugins as they'll likely provide the functionality you'd like without much custom work. Of course since you're dealing with large images it's also best to keep an eye on the resource management; a good plugin should be fairly efficient but others may be slow or resource intensive.
Check this jquery plugin:ScrollMagic
usage: taken from github
The basic ScrollMagic design pattern is one controller, which has several scenes attached.
Each scene has a definite start and end position and defines what happens when the container is scrolled to the specific offset.
/*
Basic workflow example
*/
// init controller
var controller = new ScrollMagic();
// assign handler "scene" and add it to controller
var scene = new ScrollScene({duration: 100})
.setPin("#my-sticky-element") // pins the element for a scroll distance of 100px
.addTo(controller); // add scene to controller
// adding multiple scenes at once
var scene2 = new ScrollScene();
var scene3;
controller.addScene([
scene2,
scene3 = new ScrollScene({duration: 200}), // add scene and assign handler "scene2"
new ScrollScene({offset: 20}) // add anonymous scene
]);
My goal is to make a fixed div appear at the top of a page once someone scrolls a certain amount of pixels down the page. Basically once the header section is out of view, this div will appear.
I've looked at code similar to what I want; however, haven't seen anything that would allow me to easily modify the pixel count from the top of the page (if possible).
Here is a piece of code I saw dealing with making divs appear by scrolling.
// Get the headers position from the top of the page, plus its own height
var startY = $('header').position().top + $('header').outerHeight();
$(window).scroll(function(){
checkY();
});
function checkY(){
if( $(window).scrollTop() > startY ){
$('.fixedDiv').slideDown();
}else{
$('.fixedDiv').slideUp();
}
}
// Do this on load just in case the user starts half way down the page
checkY();
I just want to know how to make it appear. If someone knows of a piece of code already in tact with a slide up and slide down animation, that would be greatly appreciated as well but not required.
window.addEventListener("scroll",function() {
if(window.scrollY > 500) {
$('.fixedDiv').slideDown();
}
else {
$('.fixedDiv').slideUp();
}
},false);
Brandon Tilley answered my question in a comment...
You would change the first line, with the startY, to be the specific Y
position you need, rather than calculating based on the header's
position and height. Here's an updated fiddle:
jsfiddle.net/BinaryMuse/Ehney/1
window.addEventListener("scroll",function() {
$('.fixedDiv')[(window.scrollY > 500)?"slideDown":"slideUp"]();
},false);
DEMO: http://jsfiddle.net/DerekL/8eG2A/
What would be computationally-efficient ways to select elements touching the top edge of browser window viewport as the page is scrolled?
See attached image. Green elements are selected because they are touching the top edge.
UPDATE
An example of how I'll use this is to fade elements that are going off-screen. There may be hundreds of them on the page. Imagine a page like Pinterest. Computing offset and scrollTop for hundreds of them at the rate of scroll event, even if throttled still feels really inefficient.
This is what I came up with. I think that it could be improved upon by caching the scrollTop values, but this is pretty good. I have included the framework for caching the boxtops, but not the implementation code. I have also only implemented scrolling down to hide divs. I have left reshowing them on upscroll as an exercise for you.
When the window is scrolled we get the last hidden div. We know that everything before this div is already hidden. Then use a 'while next element is off the screen' hide it. As soon as a div isn't off the screen we abort. Thus saving time from iterating through the entire list.
http://jsfiddle.net/kkv3h/2/
//track whether user has scrolled up or down
var prevScrollTop = $(document).scrollTop();
$(document).scroll(function() {
var currentScrollTop = $(this).scrollTop();
if (currentScrollTop > prevScrollTop) {
//down
var lasthiddenbox = $('.fadeboxhidden:last');
var nextbox = (lasthiddenbox.length > 0) ? lasthiddenbox.next('.fadebox') : $('.fadebox:first');
while (nextbox.length) {
console.log('box: ' + nextbox.offset().top + ' scroll: ' + currentScrollTop);
if (nextbox.offset().top < currentScrollTop) {
nextbox.animate({ opacity: 0 }, 3000).addClass('fadeboxhidden');
}
else { return; }
nextbox = nextbox.next('.fadebox:first');
}
} else {
//up
}
prevScrollTop = currentScrollTop ;
});
//create an object to hold a list of box top locations
var boxtops = new Object;
//gather all boxes and store their top location
$('.fadebox').each( function(index) {
//you may want to dynamically generate div ids here based on index. I didn't do this
//because i was already using the id for positioning.
var divid = $(this).prop('id');
boxtops[divid] = $(this).offset().top;
//console.log(boxtops[divid]);
});
I'm thinking the best way would be that you could mark elements you want to determine hit testing with by some class, say "hit-test-visible" or something. Then, for those elements, on the scroll event, you should be able to find their offset compared to the document - see jQuery offset, and then based on the scroll value, if the offset is less than the scroll, and the offset + element height is greater than the scroll offset, then the element should be "touching" the top edge.