ScrollIntoView() causing the whole page to move - javascript

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.

Related

Javascript Sticky Element onscroll avoid jumping

I'm trying to fix an element when I scroll down.
The code works fine but as you can see at the following link, the bar with the 3 yellow buttons jumps when it is about to reach the Top!
There seems to be some template css class causing this problem,
but I can't figure out which one
This is the code
var fixmeTop = $('.pulsanti').offset().top;
$(window).scroll(function() {
var currentScroll = $(window).scrollTop();
if (currentScroll >= fixmeTop) {
$('.pulsanti').css({
position: 'fixed',
top: '0',
zIndex: '1020'
});
} else {
$('.pulsanti').css({
position: 'relative'
});
}
});
thank you everyone
I think the problem is that fixmeTop is assigned before some elements are loaded:
var fixmeTop = $('.pulsanti').offset().top;
My chrome console outputs this:
> fixmeTop
< 2314.3374633789062
> $('.pulsanti').offset().top;
< 3207.5623779296875
You can see that the fixmeTop variable is not the real element position.
Maybe you need to assign it in body.onload()?
Update
After executing fixmeTop = $('.pulsanti').offset().top; in the chrome console after the page is loaded, I can verify that the element is sticking smoothly to the top of the page.
Adding this code fragment will create a handler function to be called when the window's load event fires. That will happen after everything (divs, images) is loaded. This way the fixmeTop will contain the true element position.
window.onload = function () {
fixmeTop = $('.pulsanti').offset().top;
}
You can keep the variable declaration in the original script, or remove it and add var here.
Also, bear in mind that it will not work until everything on the page is loaded and that it will not be valid when anything on the page moves - eg. page resize, divs rearranged. You would have to add listeners for every such event to adjust the value accordingly. Something like this may be useful:
function updateFixmeTop() {
fixmeTop = $('.pulsanti').offset().top;
}
window.addEventListener("resize", updateFixmeTop);
edit: changed element body to window in event listener
Hope it helps!
Update2
Let's say you added the code for resize event listener and scrolled past the point where the element should stick to the top. If you were to resize window fixmeTop would be assigned a value that corresponds to the element being on top of the page, and not the original element position.
To fix this you may want to add a dummy element without any margin or padding:
<div id="elementJustBeforeFixmeTop"></div> <! -- dummy element -->
<div class="pulsanti"> <! -- sticky element -->
...
</div>
And refer to its position instead of the sticky element
fixmeTop = $('#elementJustBeforeFixmeTop').offset().top;
This way you will store the scroll position at which you want the element to stick and it will not be different if the element is already at the top.
You may want to check if your page doesn't change its layout somewhere else and also update the fixmeTop value there to ensure it's always pointing at the right element.

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/

How would I implement a vertical version of this horizontal dynamic header?

On The Economist website, there is a horizontal header that only appears after you scroll down the page once. See here:
http://www.economist.com/blogs/asiaview/2010/12/china_and_nobel_peace_prize
What I want is a vertical version of this that would come out of the left or right side of the page and expand over the page content that is already in place.
Anyone know of an existing plugin or how I could build something like that in jQuery?
Here's a simple jQuery plugin that should work for you:
(function($) {
$.fn.scrollToast = function(options) {
var settings = options || {};
var offset = settings.offset;
var toast = settings.toast;
var $toast = $(toast);
var hidden = true;
// prepare the toast:
$toast.css({
display: 'none',
position: 'fixed',
top: '0px',
left: '0px',
zIindex: '1',
overflow: 'hidden'
});
this.bind("scroll", function($event) {
var top = $(this).scrollTop();
if ((top >= offset && hidden) || (top < offset && !hidden)) {
hidden = !hidden;
$toast.animate(
{width: "toggle"});
}
});
};
})(jQuery);
Usage: $(window).scrollToast({toast: "#toast", offset: 50});, where #toast is a selector indicating the element to slide out, and offset is how long you want the user to scroll before the toast appears.
Notes:
Uses CSS position:fixed and an elevated z-index to make the toast element appear on top of other content.
When the target element is scrolled to a value equal to or beyond offset, the toast element is slid out (it is initially hidden).
When the target element is scrolled to a value less than offset the toast element is slid back in.
Could easily be extended to show the toast on the other edge of the screen or the top or bottom.
Will probably work on any scrollable element, but I've used $(window) because it seems to fit the use case you described.
See a working example here: http://jsfiddle.net/andrewwhitaker/56dTA/
Yes, it's pretty easy to build:
You create a:
<div id="hiddenmenu">
This Appears on scrolldown
</div>
This div should be absolute positionend, and display:none;
With the jQuery, on scroll-down you use $('#hiddenmenu').show();
That's pretty much it, if you need the full code, just ask and I'll post it.

Detect when window vertical scrollbar appears

Is there a simple and reliable solution for detecting window vertical scrollbar appears/disappears?
window.onresize isn't triggered when after JavaScript DOM manipulation page becomes high enough for appearing scrollbar.
In this very similar post Detect if a page has a vertical scrollbar described solution how to detect whether scrollbar is present or not, but I need to know when exactly it appears.
Sorry to bring this back from the dead but I have just run in to this limitation and came up with my own solution. It's a bit hacky but stick with me ...
The idea is to add a 100% width invisible iframe to the page and listen for resize events on it's internal window. These events will pick up changes not only to the outer window's size but also when scrollbars get added to or removed from the outer window.
It triggers a regular window resize event so it requires no extra code if you are already listening for window resize.
Tested in IE9 and Chrome/Firefox latest - could maybe be made to work in older IEs but my project doesn't support those so I haven't tried.
https://gist.github.com/OrganicPanda/8222636
Based on OrganicPanda's answer, came up with this jquery thing
$('<iframe id="scrollbar-listener"/>').css({
'position' : 'fixed',
'width' : '100%',
'height' : 0,
'bottom' : 0,
'border' : 0,
'background-color' : 'transparent'
}).on('load',function() {
var vsb = (document.body.scrollHeight > document.body.clientHeight);
var timer = null;
this.contentWindow.addEventListener('resize', function() {
clearTimeout(timer);
timer = setTimeout(function() {
var vsbnew = (document.body.scrollHeight > document.body.clientHeight);
if (vsbnew) {
if (!vsb) {
$(top.window).trigger('scrollbar',[true]);
vsb=true;
}
} else {
if (vsb) {
$(top.window).trigger('scrollbar',[false]);
vsb=false;
}
}
}, 100);
});
}).appendTo('body');
This will trigger 'scrollbar' events on the window, if they appear/dissapear
Works on chrome/mac, at least. now, someone extend this to detect horizontal scrollbars :-)
The Scoop
It is possible to detect changes in scrollbar visibility by using ResizeObserver to check for changes in the size of the element that may take scrollbars and changes in the size of its contents.
Rationale
I started implementing a solution with the <iframe> method but quickly found that having a complete implementation required breaking the separation of concerns among the views of my application. I have a parent view which needs to know when a child view acquires a vertical scrollbar. (I don't care about the horizontal scrollbar.) I have two situations that may affect the visibility of the vertical scrollbar:
The parent view is resized. This is under direct control of the user.
The child view's contents becomes bigger or smaller. This is under indirect control of the user. The child view is showing the results of a search. The quantity and type of results determine the size of the child view.
I found that if I used <iframe> I'd have to muck with the child view to support the parent's needs. I prefer the child to not contain code for something which is purely a concern of the parent. With the solution I describe here, only the parent view needed to be modified.
So in looking for a better solution, I found this answer by Daniel Herr. He suggests using ResizeObserver to detect when a div's dimensions change. ResizeObserver is not yet available natively across browsers but there is a robust ponyfill/polyfill that I use for support in cases where native support is not available. (Here is the spec for ResizeObserver.)
Proof-of-Concept
I use this polyfill in its ponyfill mode. That way, the global environment remains untouched. This implementation relies on window.requestAnimationFrame, and will fall back on setTimeout for platforms that don't support window.requestAnimationFrame. Looking at the support for requestAnimationFrame on "Can I use...?", what I see there does not bother me. YMMV.
I have a live proof-of-concept. The key is to listen to changes in size on the DOM element that can accept scroll bars (the element with id container, in green) and listen to changes in size on the content that may need scrolling (the element with id content). The proof-of-concept uses interact.js to manage a resizer element (with id resizer, in blue) that allows resizing container. If you drag the bottom right corner of resizer, it will resize both resizer and container. The two buttons allow simulating changes in the size of the contents displayed by container.
I'm using this method in code that is currently at a pre-release stage, meaning it passed tests on multiple browsers, and is being evaluated by stakeholders, but is not yet in production.
The HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="interact.js#*" data-semver="1.0.26" src="//rawgit.com/taye/interact.js/v1.0.26/interact.js"></script>
<script src="//rawgit.com/que-etc/resize-observer-polyfill/master/dist/ResizeObserver.global.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="resizer">
<div id="container">
<ul id="content">
<li>Something</li>
</ul>
</div>
</div>
<button id="add">Add to content</button>
<button id="remove">Remove from content</button>
<p>Scroll bar is: <span id="visibility"></span></p>
<ul id="event-log"></ul>
<script src="script.js"></script>
</body>
</html>
The JavaScript:
var container = document.getElementById("container");
var resizer = document.getElementById("resizer");
interact(resizer)
.resizable({
restrict: {
restriction: {
left: 0,
top: 0,
right: window.innerWidth - 10,
bottom: window.innerHeight - 10
}
}
})
.on('resizemove', function(event) {
var target = resizer;
var rect = target.getBoundingClientRect();
var width = rect.width + event.dx;
var height = rect.height + event.dy;
target.style.width = width + 'px';
target.style.height = height + 'px';
});
var content = document.getElementById("content");
var add = document.getElementById("add");
add.addEventListener("click", function() {
content.insertAdjacentHTML("beforeend", "<li>Foo</li>");
});
var remove = document.getElementById("remove");
remove.addEventListener("click", function() {
content.removeChild(content.lastChild);
});
// Here is the code that pertains to the scrollbar visibility
var log = document.getElementById("event-log");
content.addEventListener("scrollbar", function () {
log.insertAdjacentHTML("beforeend", "<li>Scrollbar changed!</li>");
});
var visiblity = document.getElementById("visibility");
var previouslyVisible;
function refreshVisibility() {
var visible = container.scrollHeight > container.clientHeight;
visibility.textContent = visible ? "visible" : "not visible";
if (visible !== previouslyVisible) {
content.dispatchEvent(new Event("scrollbar"));
}
previouslyVisible = visible;
}
// refreshVisibility();
var ro = new ResizeObserver(refreshVisibility);
ro.observe(container);
ro.observe(content);
The CSS:
* {
box-sizing: border-box;
}
#container {
position: relative;
top: 10%;
left: 10%;
height: 80%;
width: 80%;
background: green;
overflow: auto;
}
#resizer {
background: blue;
height: 200px;
width: 200px;
}
If you're using AngularJS, you can use a directive to detect when the width changes (assuming the appearing/disappearing scrollbar is a vertical one):
app.directive('verticalScroll', function($rootScope){
return {
restrict: 'A',
link: function (scope, element) {
scope.$watch(
function() {
return element[0].clientWidth;
},
function() {
$rootScope.$emit('resize');
}
);
}
}
});
This fires an event on the root scope which other directives or controllers can listen for.
The watch is fired by the angular digest loop, so this relies on Angular having loaded/removed the extra content which has caused your scrollbar to appear/disappear.
Dynamically Detect Browser Vertical Scrollbar Event by
comparing window.innerWidth to getBoundingClientRect()
of a DIV element using Javascript. Tested with latest
IE FF Chrome. See documentation here
It's all about when you need to determine the scrollbar's visibility.
The OP speaks of a time "after JavaScript DOM manipulation". If that manipulation happens in your code, then that's the time for checking if the scrollbar is visible. Why do you need an event in addition to that? How is it that you don't know when this DOM manipulation occurs?
I realize this is an old question, but I'm just now dealing with this in a pure javascript project, and I have no issue knowing when to check for scrollbar visibility. Either a user event fires, or a system event fires, and I know when the DOM manipulation occurs because I'm causing it via javascript. I don't see a case where that javascript DOM manipulation is outside of my code's awareness.
Maybe a scrollbarVisibilityChange event would be convenient, but it's certainly not necessary. This strikes me as a non-issue, 9 years later. Am I missing something?
If you only need to detect the scroll appearance on Windows browsers (except IE), here's my solution with Resize Observer API for vertical scroll as an example.
Idea
Append <div> with position: fixed to <body>
Make it 100% width and observe for size changes
The appearance of the scroll reduces the <div>'s width, which in turn calls the observer callback.
Why only Windows browsers?
Mobile and macOS browsers have a disappearing scroll that is taken out of the document flow and doesn't affect the page layout.
Why should the position be fixed and not absolute?
Element with position: fixed is positioned relative to the initial containing block established by the viewport.
position: absolute may fail if the <body> is also absolutely positioned and has a different width than the viewport.
const innerWidthFiller = document.createElement('div')
innerWidthFiller.style.cssText = 'position: fixed; left: 0; right: 0'
document.body.appendChild(innerWidthFiller)
const detectScroll = () => {
const {clientHeight, scrollHeight} = document.documentElement
window.result.value = scrollHeight > clientHeight
}
const resizeObserver = new ResizeObserver(detectScroll)
resizeObserver.observe(innerWidthFiller)
#test {
border: 1px solid;
white-space: nowrap;
}
output {
font-weight: bold;
}
<button onclick="test.style.fontSize='100vh'">Enlarge the text</button>
<button onclick="test.style.fontSize=''">Reset</button>
Page scroll state: <output id="result"></output>
<hr>
<span id="test">Test element</span>

JavaScript to scroll long page to DIV

I have a link on a long HTML page. When I click it, I wish a div on another part of the page to be visible in the window by scrolling into view.
A bit like EnsureVisible in other languages.
I've checked out scrollTop and scrollTo but they seem like red herrings.
Can anyone help?
old question, but if anyone finds this through google (as I did) and who does not want to use anchors or jquery; there's a builtin javascriptfunction to 'jump' to an element;
document.getElementById('youridhere').scrollIntoView();
and what's even better; according to the great compatibility-tables on quirksmode, this is supported by all major browsers!
If you don't want to add an extra extension the following code should work with jQuery.
$('a[href=#target]').
click(function(){
var target = $('a[name=target]');
if (target.length)
{
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 1000);
return false;
}
});
How about the JQuery ScrollTo - see this sample code
You can use Element.scrollIntoView() method as was mentioned above. If you leave it with no parameters inside you will have an instant ugly scroll. To prevent that you can add this parameter - behavior:"smooth".
Example:
document.getElementById('scroll-here-plz').scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
Just replace scroll-here-plz with your div or element on a website. And if you see your element at the bottom of your window or the position is not what you would have expected, play with parameter block: "". You can use block: "start", block: "end" or block: "center".
Remember: Always use parameters inside an object {}.
If you would still have problems, go to https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
There is detailed documentation for this method.
Click here to scroll
<A name='myAnchorALongWayDownThePage"></a>
No fancy scrolling but it should take you there.
The difficulty with scrolling is that you may not only need to scroll the page to show a div, but you may need to scroll inside scrollable divs on any number of levels as well.
The scrollTop property is a available on any DOM element, including the document body. By setting it, you can control how far down something is scrolled. You can also use clientHeight and scrollHeight properties to see how much scrolling is needed (scrolling is possible when clientHeight (viewport) is less than scrollHeight (the height of the content).
You can also use the offsetTop property to figure out where in the container an element is located.
To build a truly general purpose "scroll into view" routine from scratch, you would need to start at the node you want to expose, make sure it's in the visible portion of it's parent, then repeat the same for the parent, etc, all the way until you reach the top.
One step of this would look something like this (untested code, not checking edge cases):
function scrollIntoView(node) {
var parent = node.parent;
var parentCHeight = parent.clientHeight;
var parentSHeight = parent.scrollHeight;
if (parentSHeight > parentCHeight) {
var nodeHeight = node.clientHeight;
var nodeOffset = node.offsetTop;
var scrollOffset = nodeOffset + (nodeHeight / 2) - (parentCHeight / 2);
parent.scrollTop = scrollOffset;
}
if (parent.parent) {
scrollIntoView(parent);
}
}
This worked for me
document.getElementById('divElem').scrollIntoView();
Answer posted here - same solution to your problem.
Edit: the JQuery answer is very nice if you want a smooth scroll - I hadn't seen that in action before.
Why not a named anchor?
The property you need is location.hash. For example:
location.hash = 'top'; //would jump to named anchor "top
I don't know how to do the nice scroll animation without the use of dojo or some toolkit like that, but if you just need it to jump to an anchor, location.hash should do it.
(tested on FF3 and Safari 3.1.2)
I can't add a comment to futtta's reply above, but for a smoother scroll use:
onClick="document.getElementById('more').scrollIntoView({block: 'start', behavior: 'smooth'});"
<button onClick="scrollIntoView()"></button>
<br>
<div id="scroll-to"></div>
function scrollIntoView() {
document.getElementById('scroll-to').scrollIntoView({
behavior: 'smooth'
});
}
The scrollIntoView method accepts scroll-Options to animate the scroll.
With smooth scroll
document.getElementById('scroll-to').scrollIntoView({
behavior: 'smooth'
});
No animation
document.getElementById('scroll-to').scrollIntoView();
There is a jQuery plugin for the general case of scrolling to a DOM element, but if performance is an issue (and when is it not?), I would suggest doing it manually. This involves two steps:
Finding the position of the element you are scrolling to.
Scrolling to that position.
quirksmode gives a good explanation of the mechanism behind the former. Here's my preferred solution:
function absoluteOffset(elem) {
return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);
}
It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses window.scroll. So the rest of the solution is:
function scrollToElement(elem) {
window.scroll(0, absoluteOffset(elem));
}
Voila!
As stated already, Element.scrollIntoView() is a good answer. Since the question says "I have a link on a long HTML page..." I want to mention a relevant detail. If this is done through a functional link it may not produce the desired effect of scrolling to the target div. For example:
HTML:
<a id="link1" href="#">Scroll With Link</a>
JavaScript:
const link = document.getElementById("link1");
link.onclick = showBox12;
function showBox12()
{
const box = document.getElementById("box12");
box.scrollIntoView();
console.log("Showing Box:" + box);
}
Clicking on Scroll With Link will show the message on the console, but it would seem to have no effect because the # will bring the page back to the top. Interestingly, if using href="" one might actually see the page scroll to the div and jump back to the top.
One solution is to use the standard JavaScript to properly disable the link:
<a id="link1" href="javascript:void(0);">Scroll With Link</a>
Now it will go to box12 and stay there.
I use a lightweight javascript plugin that I found works across devices, browsers and operating systems: zenscroll
scrollTop (IIRC) is where in the document the top of the page is scrolled to. scrollTo scrolls the page so that the top of the page is where you specify.
What you need here is some Javascript manipulated styles. Say if you wanted the div off-screen and scroll in from the right you would set the left attribute of the div to the width of the page and then decrease it by a set amount every few seconds until it is where you want.
This should point you in the right direction.
Additional: I'm sorry, I thought you wanted a separate div to 'pop out' from somewhere (sort of like this site does sometimes), and not move the entire page to a section. Proper use of anchors would achieve that effect.
I personally found Josh's jQuery-based answer above to be the best I saw, and worked perfectly for my application... of course, I was already using jQuery... I certainly wouldn't have included the whole jQ library just for that one purpose.
Cheers!
EDIT: OK... so mere seconds after posting this, I saw another answer just below mine (not sure if still below me after an edit) that said to use:
document.getElementById('your_element_ID_here').scrollIntoView();
This works perfectly and in so much less code than the jQuery version! I had no idea that there was a built-in function in JS called .scrollIntoView(), but there it is! So, if you want the fancy animation, go jQuery. Quick n' dirty... use this one!
For smooth scroll this code is useful
$('a[href*=#scrollToDivId]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
var head_height = $('.header').outerHeight(); // if page has any sticky header get the header height else use 0 here
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - head_height
}, 1000);
return false;
}
}
});
Correct me if I'm wrong but I'm reading the question again and again and still think that Angus McCoteup was asking how to set an element to be position: fixed.
Angus McCoteup, check out http://www.cssplay.co.uk/layouts/fixed.html - if you want your DIV to behave like a menu there, have a look at a CSS there

Categories

Resources