Get Ypostion when scrolling page - javascript

I like to know where an object is on a page,
I did that function
$(window).scroll(function () {
var elemento = $("#containerY");
var positionY = elemento.position();
$( ".valorY" ).text("top: " + positionY.top )
})
It works when page is loaded but $( ".valorY" ) don't refresh de number and always show the same when page is scrolled,
What is wrong?

You should use ($ window).scrollTop() to get the y-coordinate of the top border of your browser and ($ 'yourElement').scrollTop() to get its scroll-position. You can compare these to see what is on screen and what is not.

Sounds like you just need to subtract the window's scroll position from your elements position:
$(window).scroll(function () {
var elemento = $("#containerY");
var positionY = elemento.position();
$( ".valorY" ).text("top: " + (positionY.top - $(window).scrollTop()) )
})

thanks,
here is the solution!
positionY.top - topBrowsere
and the code:
$(document).ready(function(){
$(window).scroll(function(){
var elemento = $("#containerY");
var positionY = elemento.position();
var topBrowser = $(window).scrollTop();
$( ".valorY" ).text("top: " + (positionY.top - topBrowser) );
})
})

Related

How to add a class to a each li whenever you scroll to it with jquery

I have a list with many li
I'd like to add a class to each li only when I scroll to that specific li
The issue is the class is added to every li once I scroll to only 1 of them
$(window).scroll(function(e) {
var y = $(document).scrollTop();
var h = $(window).height();
var t = $('li.product');
var length = t.length;
for(var i=1;i <= length;){
var number = 'li.product:nth-child('+i+')';
if(y + h > $(number).position().top){
$(number).addClass("animate__animated animate__fadeInDown");
}
i++;
}});
Thanks in Advance
I couldn't find what's wrong with your code so I made another version of your code. You can find it at https://codepen.io/beneji/pen/RwLQLVV.
The code uses .each instead of a for loop which is a better fit in this case.
You can adjust this code to your particular case.
$(window).scroll(function(){
const scrolling_position = $(window).scrollTop()
const window_height = $(window).height()
$("li.product").each(function(){
const product_position = $(this).position().top
if(product_position <= scrolling_position + window_height)
$(this).addClass("animate__animated animate__fadeInDown") // replace this by whatever class you want
});
})
Consider the following.
$(window).scroll(function(e) {
var y = $(document).scrollTop();
var h = $(window).height();
var t = $('li.product');
t.each(function(i, el) {
if ((y + h) > $(el).position().top) {
$(el).addClass("animate__animated animate__fadeInDown");
}
});
});
This is untested as you did not provide a Minimal, Reproducible Example.
Using .each() we can iterate each of the elements. i is the Index and el is the Element itself.

check if the user has reached to bottom of the page

I am trying to trigger an event when the users scrolls down and reaches to the bottom of the page.
I searched the internet and found some posts in stackoverflow but unexpectedly the answers did not work for me.
Ex: Check if a user has scrolled to the bottom
using the answers given for the above SO post, the event I am trying to trigger is executed when reaching the top of the page and not the bottom.
Please let me know if I am going wrong:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
loadmore();
}
});
function loadmore(){
var lastProd = $('.product_div').last();
var lastProdID = $('.product_div').last().prop('id');
//console.info(lastProdID); return false;
//var val = document.getElementById("row_no").value;
$.ajax({
type: 'post',
url: 'includes/load_products.php',
data: { getresult:lastProdID },
success: function (response) {
console.log(response);
//var content = document.getElementById("all_rows");
//content.innerHTML = content.innerHTML+response;
lastProd.after(response);
// We increase the value by 10 because we limit the results by 10
// document.getElementById("row_no").value = Number(val)+10;
}
});
}
Use window.innerHeight + window.scrollY to determine bottom position and check if document.body.offsetHeight is lower (equal won't work).
Credit goes to mVChr, see here.
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
alert("bottom of the page reached");
}
};
.jump {
height: 1000px;
}
<div class="jump"></div>
check the height and offset are equal
window.onscroll = function() {
var d = document.documentElement;
var offset = d.scrollTop + window.innerHeight;
var height = d.offsetHeight;
console.log('offset = ' + offset);
console.log('height = ' + height);
if (offset === height) {
console.log('At the bottom');
loadmore(); // call function here
}
};
The only proper way to do this, at time of writing Feb/11/2022, is here: Check if a user has scrolled to the bottom in subpixel precision era
That detects bottom of scroll for any element. To do this with the "window" in a default web page, you should set element to document.documentElement or document.scrollingElement to get the result you want.
Or, apply the same Math.abs trick as in that answer with window.scrollY, but not that that does not work with scrollable in any other elements, only the documentElement (that's what element is being scrolled when saying "window scroll", and it is the root <html> element).

How to apply .on('load'), .scroll(), and .resize() to a sticky scroller

I have a functionality that sets the top position of a div (#sticky) on load and on scroll. But of course the variables will change as the size of the page changes, so I have need for the .resize() event.
When I run the code on page load and on scroll, it works fine but if I resize the page, then scroll the top position of #sticky gets set to 0.
How do I correct this problem?
$(document).ready(function(){
sticky = $('#sticky'),
stickyPadding = 80;
if($(sticky).length && ($(window).width() >= 900)){
$(sticky).css('position','relative');
$(window).on('load',function(){
getStickyMeasurements();
stickEl()();
$(window).resize(function(){
getStickyMeasurements();
});
$(window).scroll(stickEl());
});
}
});
function getStickyMeasurements(){
elHeight = $(sticky).outerHeight();
initialElToTop = $(sticky).offset().top;
dynamicStickyLimiter = $('.entry-content-extra').length ? $('.entry-content-extra').offset().top : $('footer').offset().top
stickyLimit = dynamicStickyLimiter - initialElToTop;
}
function stickEl(){
return function(){
elTopModifier = $(window).scrollTop() - initialElToTop;
if( stickyLimit <= (elTopModifier + elHeight + stickyPadding)){
stickyTopResult = stickyLimit - elHeight;
}else if($(window).scrollTop() + stickyPadding >= initialElToTop){
stickyTopResult = elTopModifier + stickyPadding;
}else{
stickyTopResult = 0;
}
$(sticky).css('top', stickyTopResult + 'px');
}
}
Also, I know the scope of my variables needs work, so if you include that in part of your answer, that would be helpful as well (but not required of an accepted answer).

jQuery absolute sidebr scrolling, stop at the top of parent and at bottom

hi guys so i have this code ive done which when scrolling the sidebar moves up from bottom to top but im stuck with how to stop the scrolling once the sidebar hits the top of the main conatiner - can someone maybe help me with this?
code is:
$(window).bind('scroll', function () {
var scrolledY = $(window).scrollTop();
$('.parallax-sidebar').css('bottom', '+' + ((scrolledY * 1.3)) + 'px');
});
I have a fiddle example here: http://jsfiddle.net/06qwtgt6/1/
Many thanks!
$(document).ready(function () {
/********************************************************************************/
/* Parallax Scrolling */
// Cache the Window object
var $window = $(window);
$('[data-type]').each(function () {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
$('div[data-type="background"]').each(function () {
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top;
$(window).bind('scroll', function () {
if (($window.scrollTop() + $window.height()) > (topOffset) &&
((topOffset + $self.height()) > $window.scrollTop())) {
var yPos = -($window.scrollTop() / $self.data('speed'));
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
}
var coords = '50% ' + yPos + 'px';
$self.css({ backgroundPosition: coords });
};
});
});
// For each element that has a data-type attribute
$('div[data-type="content"]').each(function () {
$(window).bind('scroll', function () {
var scrolledY = $(window).scrollTop();
$('.parallax-content').css('bottom', '+' + ((scrolledY * 1.3)) + 'px');
});
});
$(window).scroll(function(){
if ($(this).scrollTop() > 150) {
$('.sidebar').addClass('fixed');
} else {
$('.sidebar').removeClass('fixed');
}
});
});
CSS
.fixed {position:fixed; top:0;}
DEMO

How do I add class to body when div height is smaller than window?

I'm trying to add a class to the body if a certain divs height is smaller than the users window size. Here is my current jQuery script. It doesn't work very well, and I don't get any errors. Not sure what I'm doing wrong.
Thanks
jQuery(document).ready(function($) {
var $window = $(window);
var $pageHeight = $('.wrap').height();
function checkWidth() {
var windowsize = $window.height();
if (windowsize < $pageHeight) {
$('body').addClass('need-padding');
}
}
checkWidth();
$(window).resize(checkWidth);
});
Try this... no need to create separate function :
$(window).resize(function(){
var $windowHeight = $(window).height();
var $blockHeight = $('.wrap').height();
if ($blockHeight < $windowHeight ) {
//console.log($windowHeight+" Window Height");
//console.log($blockHeight+" Block Height");
$('body').addClass('need-padding');
}
});
Generally, the code looks ok. But if your $('.wrap') has margins or borders, you might want to use use .outerHeight() instead of .height().
Here's a fiddle that shows what's going on:
http://jsfiddle.net/4fqb8t1q/
$(document).ready(function() {
checkWidth();
$(window).resize(checkWidth);
});
function checkWidth() {
var $pageHeight = $('.wrap').height();
alert($(window).height() + " < " + $pageHeight);
if ($(window).height() < $pageHeight) {
$('body').addClass('need-padding');
}
}

Categories

Resources