I have a deep page with a deep footer
I want to use some jQuery to trigger an event when the top of the footer comes into view
I have looked and tried using
var scrollTop = jQuery (window).scrollTop();
but it just gives the position when you load, and it doesn't change as you scroll
Any ideas please
You can use my script on this answer: Pause and play video when in viewport
Fiddle: http://jsfiddle.net/pwhjk232/
$(document).ready(function() {
var inner = $(".inner");
var elementPosTop = inner.position().top;
var viewportHeight = $(window).height();
$(window).on('scroll', function() {
var scrollPos = $(window).scrollTop();
var elementFromTop = elementPosTop - scrollPos;
if (elementFromTop > 0 && elementFromTop < elementPosTop + viewportHeight) {
inner.addClass("active");
} else {
inner.removeClass("active");
}
});
})
Related
I'm trying to change the Z index of an image according to the scroll position,currently in chrome (but it should be working on all broswers).
anyway, it's not working on chrome, unless I get into inspection mode and I don't understand why it's only working in inspection mode?
this is the script:
$( window ).scroll(function() {
var scrollTop = $(window).scrollTop();
if ($(this).scrollTop()>700) {
document.getElementById("back-ground-image").style.zIndex = "-9";
console.log("-9");
} else {
document.getElementById("back-ground-image").style.zIndex = "-19";
console.log("-19");
}
});
Problem
What you need is $(document) not $(window).
By default, you scroll the $(document), not the $(window).
However, when you open your Chrome DevTools, the $(window) is not being scrolled which is why your code works.
To fix the issue, change $(window).scroll() to $(document).scroll() and $(window).scrollTop() to $(document).scrollTop()
Improvements
1. Use jQuery functions
Also, if you're already using jQuery, why not use jQuery selectors and .css():
$("#back-ground-image").css('zIndex', '-9')
instead of
document.getElementById("back-ground-image").style.zIndex = "-9";
2. Use DRY code
(Don't Repeat Yourself)
If you follow recommendation #1, why not set $("#back-ground-image") to a variable instead of repeating it twice.
$(document).scroll(function() {
var scrollTop = $(document).scrollTop(),
$bkImg = $("#back-ground-image");
if ($(this).scrollTop() > 700) {
$bkImg.css('zIndex', '-9');
console.log("-9");
} else {
$bkImg.css('zIndex', '-19');
console.log("-19");
}
});
Otherwise, you could use:
$(document).scroll(function() {
var scrollTop = $(document).scrollTop(),
background = document.getElementById("back-ground-image");
if ($(this).scrollTop()>700) {
background.style.zIndex = "-9";
console.log("-9");
} else {
background.style.zIndex = "-19";
console.log("-19");
}
});
I am trying to make a jQuery code so that my Menu will be hidden on the top section of a page and appear when it is at or past a certain div ID. I have written what I best can to achieve this but is not working. Can anyone help me configure it properly? Thank you.
jQuery (function($){
var topHeader = $('#top-header');
var mainSlider = $('#pbf-main-slider');
if (topHeader >= mainSlider) {
topHeader.show();
} else {
topHeader.hide();
}
});
menu hidden area
menu show area
Final Outcome (I added another section of the menu that needed this function)
jQuery (function($){
var topHeader = $('#top-header');
var mainHeader = $('#main-header');
var mainSlider = $('#pbf-main-slider');
var mainSliderHeight = mainSlider.outerHeight(true);
$(window).scroll(function () {
var scrollTop = $(this).scrollTop(); //get the scroll position
if (scrollTop >= mainSliderHeight) {
topHeader.slideDown(1000);
mainHeader .slideDown(1000);
}
else {
topHeader.hide(500);
mainHeader .hide(500);
}
})
});
you should get the height of the main slider, like this:
var mainSlider = $('#pbf-main-slider');
var mainSliderHeight = mainSlider.outerHeight(true);
then make the top bar appear if the scroll is past the mainSlider's height, like this:
$(window).scroll(function () {
var scrollTop = $(this).scrollTop(); //get the scroll position
if (scrollTop >= mainSliderHeight) {
topHeader.show();
}
else {
topHeader.hide();
}
}
I need a script which toggle a class when another class or section is visible in the viewport (during scrolling).
Here I have an script which works for precised distance from top, but can somebody help me to modify it for my needs?
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('#viewport').addClass('turn_on');
} else {
$('#viewport').removeClass('turn_on');
}
});
A couple of things. First the scroll event (as well as the resize event) fire multiple times. Traditionally, developers have used something called debouncing to limit the number of times a function fires. I've never got it to work correctly, so instead I check if a condition is met before continuing. You are basically doing this already.
var bool = false
$(window).on('scroll', function(){
if(!bool){
bool = true;
//fire the function and then turn bool back to false.
};
});
The next thing you need is to identify the element to add the class to. Let's say it has an id of foo.
var yOffset = $('#foo').offset().top;
From here, you'll need to compare the current vertical scroll position with that of the yOffset. You may also need to add the height of the element for when it scrolls out of frame.
var elHeight = $('#foo').height();
The element should be completely in frame with the $(window).scrollTop() equals the yOffset and out of frame when the $(window).scrollTop() is greater than yOffset + elHeight.
This is all assuming the element isn't in the frame to begin with. If it is, it will be trickier but it's a start.
Working fiddle
Try to add function that detect if element passed in argument is visible :
function isVisisble(elem){
return $(elem).offset().top - $(window).scrollTop() < $(elem).height() ;
}
$(window).scroll(function(){
if (isVisisble( $('your_element') ))
$('#viewport').addClass('turn_on');
} else {
$('#viewport').removeClass('turn_on');
}
});
Hope this helps.
Thx everyone for help.
Here I found the solution: LINK
And here is the modified script:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * 0.1,
gridBottom = windowHeight * 1;
$(window).on('scroll', function () {
$('.inner').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).addClass('on');
}
});
});
});
I have this page:
I want to capture on which div I am while I'm scrolling.
I know If I use:
if( $(document).scrollTop() > $('#div1').position().top) {
console.log('Div1')
}
...it will capture the div1 but instead of using this code for every div I want to set 1 snippet for all divs
Something like:
var a = // The div i am at
if( $(document).scrollTop() > $(a).position().top) {
console.log($(a).attr('id'))
}
I am looking something like the viewport: http://www.appelsiini.net/projects/viewport/3x2.html
Can I achieve that without a plugin, simply 2-3 lines?
Here's a nice way to do it. You may want to optimize the '<=' with a pixel offset to improve user experience and move the div selector ($divs) outside the callback to increase performance. Have a look at my fiddle: http://jsfiddle.net/brentmn/CmpEt/
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var $divs = $('div');
var top = $.grep($divs, function(item) {
return $(item).position().top <= winTop;
});
});
Just throw it into a loop.
var list = [];
$("div").each(function(index) {
if( $(document).scrollTop() > $(this).position().top)
list.push($(this));
});
alert(list);
The list will than have every div that is within your viewport.
I'd suggest using the jQuery Inview plugin:
https://github.com/protonet/jquery.inview
Well maintained Plugin that detects whatever content is in the viewer currently, enabling you to bind functions to an inview event. So as soon as your div is in view you could fire off all the relevant functions you wanted and then again when it has left the users view. Would be great for your needs.
$(window).scroll(function () {
$("#privacyContent div").each(function () {
var bottomOffset = ($(this).offset().top + $(this).height());
console.log("Botom=",bottomOffset ,"Win= ", $(window).scrollTop());
if (bottomOffset > $(window).scrollTop()) {
$("#menu a").removeClass("active");
// console.log("Div is= ",$(this).attr('id'));
$("#menu a[href='#" + $(this).attr('id') + "']").addClass("active");
$(".b").removeClass("fsActive");
var div = $(this);
div.find(".b").addClass("fsActive");
return false;
}
});
});
I do it like this it works fine it detect all div id
I have a div layer with overflow set to scroll.
When scrolled to the bottom of the div, I wanna run a function.
The accepted answer was fundamentally flawed, it has since been deleted. The correct answer is:
function scrolled(e) {
if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {
scrolledToBottom(e);
}
}
Tested this in Firefox, Chrome and Opera. It works.
I could not get either of the above answers to work so here is a third option that works for me! (This is used with jQuery)
if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) {
//do stuff
}
Hope this helps anyone!
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)
{
//your code here
}
I too searched it and even after checking all comments here and more,
this is the solution to check if reached the bottom or not.
OK Here is a Good And Proper Solution
You have a Div call with an id="myDiv"
so the function goes.
function GetScrollerEndPoint()
{
var scrollHeight = $("#myDiv").prop('scrollHeight');
var divHeight = $("#myDiv").height();
var scrollerEndPoint = scrollHeight - divHeight;
var divScrollerTop = $("#myDiv").scrollTop();
if(divScrollerTop === scrollerEndPoint)
{
//Your Code
//The Div scroller has reached the bottom
}
}
This worked for me:
$(window).scroll(function() {
buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer ) {
doThing();
}
});
Must use jQuery 1.6 or higher
I found an alternative that works.
None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.
Implemented solution:
function IsScrollbarAtBottom() {
var documentHeight = $(document).height();
var scrollDifference = $(window).height() + $(window).scrollTop();
return (documentHeight == scrollDifference);
}
Resource: http://jquery.10927.n7.nabble.com/How-can-we-find-out-scrollbar-position-has-reached-at-the-bottom-in-js-td145336.html
Regards
I created a event based solution based on Bjorn Tipling's answer:
(function(doc){
'use strict';
window.onscroll = function (event) {
if (isEndOfElement(doc.body)){
sendNewEvent('end-of-page-reached');
}
};
function isEndOfElement(element){
//visible height + pixel scrolled = total height
return element.offsetHeight + element.scrollTop >= element.scrollHeight;
}
function sendNewEvent(eventName){
var event = doc.createEvent('Event');
event.initEvent(eventName, true, true);
doc.dispatchEvent(event);
}
}(document));
And you use the event like this:
document.addEventListener('end-of-page-reached', function(){
console.log('you reached the end of the page');
});
BTW: you need to add this CSS for javascript to know how long the page is
html, body {
height: 100%;
}
Demo: http://plnkr.co/edit/CCokKfB16iWIMddtWjPC?p=preview
This will actually be the correct answer:
function scrolled(event) {
const container = event.target.body
const {clientHeight, scrollHeight, scrollY: scrollTop} = container
if (clientHeight + scrollY >= scrollHeight) {
scrolledToBottom(event);
}
}
The reason for using the event is up-to-date data, if you'll use a direct reference to the div you'll get outdated scrollY and will fail to detect the position correctly.
additional way is to wrap it in a setTimeout and wait till the data updates.
Take a look at this example: MDN Element.scrollHeight
I recommend that check out this example: stackoverflow.com/a/24815216... which implements a cross-browser handling for the scroll action.
You may use the following snippet:
//attaches the "scroll" event
$(window).scroll(function (e) {
var target = e.currentTarget,
scrollTop = target.scrollTop || window.pageYOffset,
scrollHeight = target.scrollHeight || document.body.scrollHeight;
if (scrollHeight - scrollTop === $(target).innerHeight()) {
console.log("► End of scroll");
}
});
Since innerHeight doesn't work in some old IE versions, clientHeight can be used:
$(window).scroll(function (e){
var body = document.body;
//alert (body.clientHeight);
var scrollTop = this.pageYOffset || body.scrollTop;
if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) {
loadMoreNews();
}
});
To do the same in React/JSX, here is the snippet.
export const scrolledToEnd = event => {
const container = event.target;
if (container.offsetHeight + container.scrollTop >= container.scrollHeight) {
return true;
}
return false;
};
And in your component add
<Component onScroll={scrolledToEnd}>
There is experimental onscrollend event https://developer.mozilla.org/en-US/docs/Web/API/Document/scrollend_event
For now works only in firefox 109+, if other browsers catch up will be very nice.
Have polyfill for that https://github.com/argyleink/scrollyfills
Use like
import "scrollyfills";
...
scrollContainer.addEventListener(
"scrollend",
(ev) => { console.log('scroll END') }
);
I found this methode to get the end of the scroll :
let TheBody = document.getElementsByTagName("body"); // I choose the "body" element for my exemple
function OnScrolling(){ // put this on a scrolling EVENT
let ScrollEnd = TheBody[0].scrollHeight - window.innerHeight; // this is the scroll end Pixel
if (ScrollEnd.toFixed() == window.scrollY.toFixed()){
//do stuff
}
}
Okay now for your DIV or any other element that have a scrolling I found this method on JavaScript :
let D = document.getElementById("D1"); // I gave "D1" as id to my div
// this one is to calculate the scroll end Pixels
let Calc = D.scrollHeight - D.clientHeight;
function ScrollingInD1() {
//this one is to calculate the scrolling percent while going through the <div> it can help for "Responsivity"
let percent = (D.scrollTop * 100) / Calc;
if (D.scrollTop == Calc) {
// do Stuffs
}
}