'Endless scroll' in a div on a web page - javascript

I want to create a div containing endless scrollable content in a page.
For recognizing the end of the scrollable content in order to load more data from the data base I've written the following:
$(window).scroll(function(){
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
var scrolltrigger = 0.95;
if ((wintop/(docheight-winheight)) > scrolltrigger) {
lastAddedLiveFunc();
}
});
Question: The following code is for creating the endless scroll which fits in the entire webpage, but how can I write the same for a 'div' inside a web page?
(Hint: An exact similar thing is the Ticker on Facebook, on the right side which shows the recent activities of your friends in real time.)

The principle is the exact same. The div will be your browser viewport, and the div content is your document. You just need to exchange
$(window).scroll() --> $("#someDiv").scroll()
$(window).scrollTop() --> $("#someDiv").scrollTop()
$(document).height() --> $("#someDiv")[0].scrollHeight
$(window).height() --> $("#someDiv").height()
and it should work.
Note that:
scrollHeight is a property, not a function.
scrollHeight isn't jQuery, so you need to obtain it from the actual javascript element of the selector, hence the [0] addition. Another way is to use $("#someDiv").prop("scrollHeight").

$("#yourdiv").scroll(function(){
//your logic
}
You can use your div instead of window
For example
$('#yourdiv').scrollTop() // etc

use this
// get box div position
var box = document.getElementById('box').offsetTop;
window.onscroll = function(){
// get current scroll position
var scroll_top = document.body.scrollTop || document.documentElement.scrollTop;
document.getElementById('scbox').innerText = scroll_top + ' ' + box;
// if current scroll position >= box div position then box position fixed
if(scroll_top >= box)
document.getElementById('box').style.position = 'fixed';
else
document.getElementById('box').style.position = 'relative';
}

Related

jQuery "unstick" box when scrolling before a certain threshold

I have a box that needs to stick, and I am using position: fixed CSS for that when it reaches the bottom of the page while scrolling, and then unstick while scrolling back up past that threshold. Below is my jQuery code:
$(window).scroll(function() {
var wHeight = $(window).height();
var stickyTop = $('.threshold').offset().top;
var xxx = stickyTop - wHeight;
var windowTop = $(window).scrollTop();
if ( windowTop > xxx ) {
console.log(windowTop)
$('.box').addClass("sticky")
} else {
$('.box').removeClass("sticky")
}
});
I don't understand why my else state doesn't work. And it's weird that the console.log kicks in late.
Here's a complete pen: https://codepen.io/frontend2020/pen/vYjJBma?editors=1010
Thanks for helping!
This kind of sticking effect can be easily done with CSS. If you want something similar like this YouTube video which was captured on this site, you just need two nested divs (i.e.div>div).
The parent div must has larger height (let's say 1000px) and child div can be anything less than the parent div (let's say 200px). Then you just need to apply position: sticky; to child div.
That will do the trick.

Get the position of div on page scroll

Hi Guys,
I'm not so good with jQuery and javascript.
I will make a script that take the position of my div and when it's on the top of the page it make something.
Example:
I have a menu. When i scroll the page and my div arrive at the top (or better at 100/200px from top), something in my menu changes...
I hope somebody can help me.
Thanks.
You should use the jQuery offset() scrollTop() and scroll() methods to achieve this.
http://api.jquery.com/offset/
https://api.jquery.com/scrollTop/
https://api.jquery.com/scroll/
Offset returns the pixel value of the elements from the top of the page. Run this on scroll, and you can detect when the element is 100px, or 200px from the top.
Here is an example of running offset() and scrollTop() on window.scroll(), and adding/removing classes when the element has reached the top of this page. In this example, I am fixing the $mainMenuBar to the top of the page when the user scrolls past it, and un-fixing it when the user scroll back up past it.
// declare vars
var $window = $(window),
$mainMenuBar = $('.anchor-tabs'),
$mainMenuBarAnchor = $('.anchor-tabs-anchor');
// run on every pixel scroll
$window.scroll(function() {
var window_top = $window.scrollTop();
var div_top = $mainMenuBarAnchor.offset().top;
if (window_top > div_top) {
// Make the div sticky.
$mainMenuBar.addClass('fixed-top');
$mainMenuBarAnchor.height($mainMenuBar.height());
}
else {
// Unstick the div
$mainMenuBar.removeClass('fixed-top');
$mainMenuBarAnchor.height(0);
}
});
Hope this helps.
You can compare the offset of your div element to how far down the page the user has scrolled.
The $(window).scrollTop() function get you how far the user has scrolled down, i.e :
$(window).scroll(function() {
var yourDiv = $("#theIdOfYourDiv");
var window_offset = yourDiv.offset().top - $(window).scrollTop();
if ( window_offset < 100 )
{
// do what you want
}
});

jQuery get current view position from top

I wish to check if my current element is in view or not. I use this condition to check that:
if ($(window).scrollTop() > $('.element').offset().top) {
//show
}
But problem is that $(window).scrollTop() is giving different results on different browser height (I'm using FireFox, first number is .scrollTop(), second - .offset().top):
now I just reduce height of firebug (so scroll bar is decreased in size):
So I can't use $(window).scrollTop() to get how mush I have scrolled in page.
Any other way how to define if element is in view?
You will need to consider these 4 base values:
Window's height
Window's scroll top
Element's offset top
Element's height
Based on that, you will have:
var windowHeight = $(window).height();
var windowScrollTop = $(window).scrollTop();
var elementHeight = $(".element").height();
var elementOffsetTop = $(".element").offset().top;
if ((elementOffsetTop <= windowScrollTop + windowHeight) && (elementOffsetTop + elementHeight >= windowScrollTop))
console.log('Visible on viewport');
Note that with this algorithm, you will be able to check if the element is visible on the viewport, independent of its height, and most importantly, considering the case when you scroll the window beyond the element.
It will say that the element is visible when the highest part or the lowest part of the element is shown on viewport.

Animate a div when an element is visible in the viewport

Im am trying to create a horizontally scrolling, one-page website where I am using divs as buttons to get the page to scroll to an element when they are clicked. I have the scrolling mechanism working but I want the divs to animate (change size or colour ect...) when the element they are linked to to is visible in the viewport. What is the best way to do this?
I'm not sure how you code is done for the scrolling because you didn't provide any code / exemple but I will try to help you in some way.
$(function(){
var sections = {},
_height = $(window).height(),
i = 0;
// Grab positions of our sections
$('.section').each(function(){
//this.name would be the attr name="" of a section but you could change to the id
sections[this.name] = $(this).offset().top;
});
$(document).scroll(function(){
var pos = $(this).scrollTop();
// Look in the sections object and see if any section is viewable on the screen.
// If two are viewable, the lower one will be the active one.
for(i in sections){
if(sections[i] > pos && sections[i] < pos + _height){
$('a').removeClass('active');
$('#nav_' + i).addClass('active');
}
}
});
});
This Code should do what you want to achive atm it's just active a 'active' class but you could do a Css3 animation as you want.

Dynamically change relatively positioned content to fixed content - bug

I have a sidebar that contains content larger than the screen. As the user scrolls down I want that content to come into view until the last bit. Then I want it to be fixed so that as much content stays on screen as possible. I actually want it to work exactly like the "Similar Questions" sidebar when you are posting a question in SO. In each of these example links scroll down. In the broken case notice how everything gets all jumpy.
Should work like this = http://jsfiddle.net/mrtsherman/G4Uqm/2/
But broken in this case = http://jsfiddle.net/mrtsherman/G4Uqm/1/
In the broken case it looks like the scroll event is being retriggered when you reach the end of the page. This then causes subsequent scroll events to trigger which then screw everything up. How can I properly handle this case? I just can't figure it out.
$(document).ready(function() {
var dynamic = false;
var topOfSidebar = $("#sidebar").offset().top;
var leftOfSidebar = $("#sidebar").offset().left;
var botOfSidebar = topOfSidebar + $("#sidebar").height();
var botOfScreen = $(window).height() + $(window).scrollTop();
//if sidebar fits on screen then use fixed version of it
if (botOfSidebar < $(window).height()) {
$("#sidebar").addClass("fixed");
$("#sidebar").css("top", topOfSidebar);
$("#sidebar").css("left", leftOfSidebar);
}
else {
dynamic = true;
}
//toggle sidebar class when user scrolls
$(window).scroll(function() {
console.log($("#sidebar").css("position"));
botOfScreen = $(window).height() + $(window).scrollTop();
//return;
if (botOfSidebar < botOfScreen && dynamic) {
$("#sidebar").addClass("fixed");
//$("#sidebar").css("bottom", 0);
//$("#sidebar").css("left", leftOfSidebar);
}
else if (dynamic) {
$("#sidebar").removeClass("fixed");
}
});
});
So I figured this one out on my own. The trick is to wrap the content in a div with a min-height attribute. If we switch the sidebar to fixed then the div holds the place of the sidebar. Therefore no more screen resizing.
.wrap creates the div
.parent gets the sidebar's parent (the new div)
add css properties where min-height is the height of the sidebar. Remove padding and margin
$("#sidebar")
.wrap('')
.parent()
.css("min-height", this.height())
.css("padding", "0px")
.css("margin", "0px");

Categories

Resources