scrollTop of element always returns 0 - javascript

Im trying to log how far down the page an element is, but in my console I keep getting 0.
window.addEventListener('scroll', function() {
var selector = document.getElementById("footer");
console.log(selector.scrollTop );
});
From reading about this there seems to be a webkit bug if the body has an overflow or height applied it. However Ive tried this in IE and Firefox, and with all my CSS disabled and I keep getting the same result.

Use offsetTop instead.
window.addEventListener('scroll', function() {
var selector = document.getElementById("footer");
console.log(selector.offsetTop);
});
Online demo - https://plnkr.co/edit/JdeFnB6IZodL0b74pO2S?p=preview
check the console output, iv'e set an interval to trigger the print

For element position relative to page top, I'd use:
console.log(selector.getBoundingClientRect().top + window.pageYOffset);
For element position relative to viewport top, I'd use:
console.log(selector.getBoundingClientRect().top);
Documentation:
getBoundingClientRect()
pageYOffset
As mentioned by Michael Zhang in the comments, selector.scrollTop tells you how many pixels the element itself has been scrolled (read more).
selector.offsetTop is the number of pixels from the top of the closest relatively positioned parent element (read more).

Related

Get element position relative to screen. (Or alternative solution)

I am aware this had been asked before, but no answer actually did the trick as far as I tested them.
Basically what I need is to change some element styles as soon as it "hits" the top border of the screen while scrolling down. This element is a 'Back to Top' button that will be sitting in a section and start following the user when they scroll pass said section.
I am not asking about CSS properties, I am asking about some JS property or method that allow me to know this. IE:
$('#back').distanceFromTopOfTheScreen() // This value will decrease as I scroll down
I know there are other soultions, but the client has asked for this behavior.
Any idea?
You can :
distance = $('#eleId')[0].getBoundingClientRect().top;
For more about getBoundingClientRect() look at the MDN Documentation
Note: This value change when you're scrolling, it gives you the distance between the top border of the element and the top of the Page
Sometimes JQuery make's everything more confusing than Native Javascript, even forgothing the very basics functions:
window.onscroll = function() { fixPosition()};
function fixPosition() {
var Yplus = 4; //number of lines in every scroll
document.getElementById('element').style.top = document.body.scrollTop + Yplus ;
}
This will allows you to move an "element" static on the window following the scroll.

Using Jquery to toggle on and off items based distance to top

I am creating a site in which there are a number of fixed background images that you scroll past. Associated with each fixed background is an image slider (or text) that is hidden until the title is clicked on. These items are all fixed positioned.
I was able to make this work by using z-index to place items in order top to bottom/first to last and then have each disappear in turn using:
$(document).scroll(function() {
$('#porttitle').toggle($(this).scrollTop() < 225);
});
However, I am unable to use this because the length pixel distance down on the page changes based on the screen size. I am pretty new to Jquery but wanted to try to use .offset .top to have the item disappear not based on the pixel length to the top of the page but instead when an element appears on the screen. This is what I have so far but it isn't seeming to work.
$(document).scroll(function() {
$('#porttitle').toggle($(this).scrollTop() < $(‘article.post-100’).offset().top);
});
Here is the link to the site: http://s416809079.onlinehome.us (not final location - just developing)
Any thoughts?
Thanks!
I think this may work for you, read the comments on the code for a line by line explanation.
Working Example
$(window).scroll(function () { // When the user scrolls
$('div').each(function () { // check each div
if ($(window).scrollTop() < $(this).offset().top) { // if the window has been scrolled beyond the top of the div
$(this).css('opacity', '1'); //change the opacity to 1
} else { // if not
$(this).css('opacity', '0'); // change the opacity to 0
}
});
});
I'm conditionally changing the opacity rather than using toggle because:
...jQuery does not support getting the offset coordinates of hidden
elements or accounting for borders, margins, or padding set on the
body element.
While it is possible to get the coordinates of elements with
visibility:hidden set, display:none is excluded from the rendering
tree and thus has a position that is undefined.
Related documentation:
.offset()
.each()
.scroll()
.scrollTop()

window scroll method flickers in IE

This may come as a huge surprise to some people but I am having an issue with the IE browser when I am using the $(window).scroll method.
My goal:
I would like to have the menu located on the left retain it's position until the scroll reaches > y value. It will then fix itself to the top of the page until the scroll returns to a < y value.
My error:
Everything seems just fine in Chrome and Firefox but when I go to Internet Explorer it would seem the browser is moving #scroller every time the scroll value changes, this is causing a moving/flickering event.
If someone could point me to a resource or give me a workaround for this I would be very grateful!
Here is a fiddle:
http://jsfiddle.net/CampbeII/nLK7j/
Here is a link to the site in dev:
http://squ4reone.com/domains/ottawakaraoke/Squ4reone/responsive/index.php
My script:
$(window).scroll(function () {
var navigation = $(window).scrollTop();
if (navigation > 400) {
$('#scroller').css('top',navigation - 220);
} else {
$('#scroller').css('top',183);
$('#scroller').css('position','relative');
}
});
You might want to take a look at the jQuery Waypoints plugin, it lets you do sticky elements like this and a lot more.
If you want to stick with your current method, like the other answers have indicated you should toggle fixed positioning instead of updating the .top attribute in every scroll event. However, I would also introduce a flag to track whether or not it is currently stuck, this way you are only updating the position and top attributes when it actually make the transition instead of every scroll event. Interacting with the DOM is computationally expensive, this will take a lot of load off of the layout engine and should make things even smoother.
http://jsfiddle.net/WYNcj/6/
$(function () {
var stuck = false,
stickAt = $('#scroller').offset().top;
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
if (!stuck && scrollTop > stickAt) {
$('#scroller').css('top', 0);
$('#scroller').css('position','fixed');
stuck = true;
} else if (stuck && scrollTop < stickAt) {
$('#scroller').css('top', stickAt);
$('#scroller').css('position','absolute');
stuck = false;
}
});
});
Update
Switching the #scroller from relative to fixed removes it from the normal flow of the page, this can have unintended consequences for the layout as it re-flows without the missing block. If you change #scroller to use an absolute position it will be removed from the normal flow and will no longer cause these side-effects. I've updated the above example and the linked jsfiddle to reflect the changes to the JS/CSS.
I also changed the way that stickAt is calculated as well, it uses .offset() to find the exact position of the top of #scoller instead of relying on the CSS top value.
Instead of setting the top distance at each scroll event, please consider only switching between a fixed position and an absolute or relative position.All browsers will appreciate and Especially IE.
So you still listen to scroll but you now keep a state flag out of the scroll handler and simply evaluate if it has to switch between display types.
That is so much more optimized and IE likes it.
I can get flickers in Chrome as well if I scroll very quickly. Instead of updating the top position on scroll, instead used the fixed position for your element once the page has scrolled below the threshold. Take a look at the updated fiddle: http://jsfiddle.net/nLK7j/2/

ScrollIntoView() causing the whole page to move

I am using ScrollIntoView() to scroll the highlighted item in a list into view.
When I scroll downwards ScrollIntoView(false) works perfectly.
But when I scroll upwards, ScrollIntoView(true) is causing the whole page to move a little which I think is intended.
Is there a way to avoid the whole page move when using ScrollIntoView(true)?
Here is the structure of my page
#listOfDivs {
position:fixed;
top:100px;
width: 300px;
height: 300px;
overflow-y: scroll;
}
<div id="container">
<div id="content">
<div id="listOfDivs">
<div id="item1"> </div>
<div id="item2"> </div>
<div id="itemn"> </div>
</div>
</div>
</div>
listOfDivs is coming from ajax call. Using mobile safari.
Fixed it with:
element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' })
see: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
You could use scrollTop instead of scrollIntoView():
var target = document.getElementById("target");
target.parentNode.scrollTop = target.offsetTop;
jsFiddle: http://jsfiddle.net/LEqjm/
If there's more than one scrollable element that you want to scroll, you'll need to change the scrollTop of each one individually, based on the offsetTops of the intervening elements. This should give you the fine-grained control to avoid the problem you're having.
EDIT: offsetTop isn't necessarily relative to the parent element - it's relative to the first positioned ancestor. If the parent element isn't positioned (relative, absolute or fixed), you may need to change the second line to:
target.parentNode.scrollTop = target.offsetTop - target.parentNode.offsetTop;
var el = document.querySelector("yourElement");
window.scroll({top: el.offsetTop, behavior: 'smooth'});
I had this problem too, and spent many hours trying to deal with it. I hope my resolution may still help some people.
My fix ended up being:
For Chrome: changing .scrollIntoView() to .scrollIntoView({block: 'nearest'}) (thanks to #jfrohn).
For Firefox: apply overflow: -moz-hidden-unscrollable; on the container element that shifts.
Not tested in other browsers.
Play around with scrollIntoViewIfNeeded() ... make sure it's supported by the browser.
in my context, he would push the sticky toolbar off the screen, or enter next to a fab button with absolute.
using the nearest solved.
const element = this.element.nativeElement;
const table = element.querySelector('.table-container');
table.scrollIntoView({
behavior: 'smooth', block: 'nearest'
});
I've added a way to display the imporper behavior of the ScrollIntoView - http://jsfiddle.net/LEqjm/258/
[it should be a comment but I don't have enough reputation]
$("ul").click(function() {
var target = document.getElementById("target");
if ($('#scrollTop').attr('checked')) {
target.parentNode.scrollTop = target.offsetTop;
} else {
target.scrollIntoView(!0);
}
});
jQuery plugin scrollintoview() increases usability
Instead of default DOM implementation you can use a plugin that animates movement and doesn't have any unwanted effects. Here's the simplest way of using it with defaults:
$("yourTargetLiSelector").scrollintoview();
Anyway head over to this blog post where you can read all the details and will eventually get you to GitHub source codeof the plugin.
This plugin automatically searches for the closest scrollable ancestor element and scrolls it so that selected element is inside its visible view port. If the element is already in the view port it doesn't do anything of course.
Adding more information to #Jesco post.
Element.scrollIntoViewIfNeeded() non-standard WebKit method for Chrome, Opera, Safari browsers.
If the element is already within the visible area of the browser window, then no scrolling takes place.
Element.scrollIntoView() method scrolls the element on which it's called into the visible area of the browser window.
Try the below code in mozilla.org scrollIntoView() link. Post to identify Browser
var xpath = '//*[#id="Notes"]';
ScrollToElement(xpath);
function ScrollToElement(xpath) {
var ele = $x(xpath)[0];
console.log( ele );
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
if (isChrome) { // Chrome
ele.scrollIntoViewIfNeeded();
} else {
var inlineCenter = { behavior: 'smooth', block: 'center', inline: 'start' };
ele.scrollIntoView(inlineCenter);
}
}
Just to add an answer as per my latest experience and working on VueJs. I found below piece of code ad best, which does not impact your application in anyways.
const el = this.$el.getElementsByClassName('your_element_class')[0];
if (el) {
scrollIntoView(el,
{
block: 'nearest',
inline: 'start',
behavior: 'smooth',
boundary: document.getElementsByClassName('main_app_class')[0]
});
}
main_app_class is the root class
your_element_class is the element/view where you can to scroll into
And for browser which does not support ScrollIntoView() just use below library its awesome
https://www.npmjs.com/package/scroll-into-view-if-needed
I found (in Chrome) I could more reliably scroll my element to the top of my parent div (without moving the page) if I scrolled from the bottom up to my element rather than from the top down to my element. Otherwise while my element would scroll into view, it would sometimes still be lower than desired within the div.
To achieve this, I am scrolling in two steps:
myScrollableDiv.scrollTop = myScrollableDiv.scrollHeight which instantly scrolls to the bottom of my scrollable div
(as per other answers here) Scroll my the element into view with animation:
myElementWithinTheScrollingDiv.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
})
Using Brilliant's idea, here's a solution that only (vertically) scrolls if the element is NOT currently visible. The idea is to get the bounding box of the viewport and the element to be displayed in browser-window coordinate space. Check if it's visible and if not, scroll by the required distance so the element is shown at the top or bottom of the viewport.
function ensure_visible(element_id)
{
// adjust these two to match your HTML hierarchy
var element_to_show = document.getElementById(element_id);
var scrolling_parent = element_to_show.parentElement;
var top = parseInt(scrolling_parent.getBoundingClientRect().top);
var bot = parseInt(scrolling_parent.getBoundingClientRect().bottom);
var now_top = parseInt(element_to_show.getBoundingClientRect().top);
var now_bot = parseInt(element_to_show.getBoundingClientRect().bottom);
// console.log("Element: "+now_top+";"+(now_bot)+" Viewport:"+top+";"+(bot) );
var scroll_by = 0;
if(now_top < top)
scroll_by = -(top - now_top);
else if(now_bot > bot)
scroll_by = now_bot - bot;
if(scroll_by != 0)
{
scrolling_parent.scrollTop += scroll_by; // tr.offsetTop;
}
}
ScrollIntoView() causes page movement. But the following code works fine for me and move the screen to the top of the element:
window.scroll({
top: document.getElementById('your-element')?.offsetParent.offsetTop,
behavior: 'smooth',
block: 'start',
})
i had the same problem, i fixed it by removing the transform:translateY CSS i placed on the footer of the page.
FWIW: I found (in Chrome 95, and Firefox 92 (all Mac)) that using:
.scrollIntoView({ behavior:'smooth', block:'center'});
on a scrollable list of options would scroll the body element a little, so I opted to use:
.scrollIntoView({ behavior:'smooth', block:'nearest'});
and select an option past the one I wanted centered (e.g. in a scrollable elem with 5 lines/options viewable, I selected the 2nd option past the one I wanted centered, thereby centering the desired element.

Scroll a div vertically to a desired position using jQuery

This is a followup question for this:
Scrollpane on the bottom, css is hacky, javascript is hard
I ended up doing the scrolling in the same way explained in the accepted answer.
Now there is a request that one item is selected somehow (eg. as an url parameter or by some javascript calls) I should scroll the pane to the item with the corresponding ID in the scrollpane. Like a link to an anchor () would work!
I want to make a javascript call like this
function scrollTo(id) {
$('#middle').magicallyScrollThatItemWouldBeVisible(itemid);
}
But this is not in jQuery (or at least I don't know of it). So is there a way to make it?
I'll post a simple jsFiddle here:
http://jsfiddle.net/ruisoftware/U6QdQ/4/
Help me write that scrollTo function!
A .animate would be fine too.
UPDATE: If it was not clear I would like it to only align to the left or right side of the panel, it it was overflowed on that side (so the minimum possible amount of scrolling happens)
It's not jQuery, just JavaScript, and I've actually never used it all, so I'm not sure how you would have to mess with it to get it to work in this situation, but there is a scrollIntoView function:
yourElement.scrollIntoView();
Since the elements have a fixed width, you can count the number of elements by using .index() + 1, and animate to this value (after subtracting the container's width).
If you want the element to be centered, use - Math.round(middle.width()/100)*50.
Fiddle: http://jsfiddle.net/U6QdQ/17/
//This code should be run on load / DOMReady
(function($){ //Run on load / DOMReady
$.fn.magicScrollTo = function(){
var middle = $("#middle");
var currentScrollLeft = middle.scrollLeft();
var width = middle.width();
var newScrollLeft = this.offset().left + currentScrollLeft - middle.offset().left;
if(newScrollLeft >= currentScrollLeft && newScrollLeft <= currentScrollLeft + width - this.outerWidth()) return;
if(newScrollLeft > currentScrollLeft){ //If the element is at the right side
newScrollLeft = newScrollLeft - width + this.outerWidth();
}
middle.animate({
scrollLeft: newScrollLeft,
}, 'fast')
}
})(jQuery);
Usage:
//Select the 4rd element, and scroll to it (eq is zero-based):
$('.item').eq(3).magicScrollTo();
Something along these lines would be a good start:
http://jsfiddle.net/vHjJ4/
This will bring the target into the centre of the carousel. I think you will have to add in some extra checks to make sure that it didn't scroll to far, for example if you targeted the first or last element...unless this is built into the scroll function (it might be).
I'm not sure I understand your question exactly, but it sounds like you're asking how to scroll horizontally to the selected item in the bottom pane. If so, try something like this:
//get the position of the element relative to the parent ("middle")
var pos = $("#itemid").position();
if (pos){
$("#middle").scrollLeft(pos.left);
}
From here, you can use the width of middle to center the item if needed.

Categories

Resources