Get scroll position using jquery - javascript

Strange request, but I need to get the current browser scroll position as a variable. What js or jquery function should I use? I need it to figure out what elements to display on the side. I've found a few things online but nothing that works for my div, just the full page.

cross browser variant
$(document).scrollTop();

Older IE and Firefox browsers attach the scrollbar to the documentElement, or what would be the <html> tag in HTML.
All other browsers attach the scrollbar to document.body, or what would be the <body> tag in HTML.
The correct solution would be to check which one to use, depending on browser
var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s = $(doc).scrollTop();
jQuery does make this a little easier, when passing in either window or document jQuery's scrollTop does a similar check and figures it out, so either of these should work cross-browser
var s = $(document).scrollTop();
or
var s = $(window).scrollTop();
jQuery scrollTop() docs
Description: Get the current vertical position of the scroll bar for
the first element in the set of matched elements or set the vertical
position of the scroll bar for every matched element.
...nothing that works for my div, just the full page
If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount
$('div').scrollTop();
If you need to get the elements distance from the top of the document, you can also do
$('div').offset().top

I believe the best method with jQuery is using .scrollTop():
var pos = $('body').scrollTop();

Use scrollTop() to get or set the scroll position.

Related

How to scroll to the bottom of a Polymer 1.0 paper-drawer-panel

I am using pure Polymer/Javascript and need to scroll to the bottom of my main panel. Since it is a scrollable element within a fixed-size container the typical JS answer
window.scrollTo(0,document.body.scrollHeight);
Does not work.
Couldn't find a direct solution so posting an the answer myself. Hope this helps someone :)
(Based on what I found here)
//Get the main paper-drawer-panel element
a = document.querySelector("paper-drawer-panel [main]")
//use the undocumented scroller property and set it to the scroller's height
a.scroller.scrollTop = a.scroller.scrollHeight
UPDATE:
I also discovered that if you select any element or container within the panel there should be scrolling methods attached to them allowing you to to scroll to the top or bottom of the panel based on the selected element.
//Get the main paper-drawer-panel element
a = document.querySelector("some-element-container-in-paper-panel");
// Passing in false scrolls to the bottom of the container, no param to the top.
a.scrollIntoView(false)
I may not comment (I need 50 points of something) but scrollIntoView() is experimental technology. Not supported by Chrome.

Using #anchors to move scrollbar with extra positioning

Is it possible to change the position of the scroll bar relative to a new hash tag?
Currently, the page scrolls to the top of the element that is targeted using #target, which is normal behaviour. Is there a way to move it so the page scrolls to, for example, 100px further down the page than the anchor tag (adding an extra 100px before the anchor tag)?
Not sure whether cunning placement of the anchor or javascript should be used. Not sure I'm really able to change the position of the anchor so im hoping for a javascript solution.
Thanks
You could combine the answer to this question: On - window.location.hash - Change?
With some extra logic:
$(function(){
var win = $(window); //cache your jq objects!
function fixScrollTop(){
win.scrollTop(win.scrollTop() + 100);
}
if(window.location.hash !== ""){
fixScrollTop();
}
win.bind('hashchange', fixScrollTop);
});
Oh, if you have control over the #anchor in the URL, you can (probably, depending on the browser compatibility you're shooting for) set it to the ID of any element with an ID to make the browser scroll to it.

Using window.onscroll event to detect page/frame scrolling

I want to postion a DIV inside a page such that it is visible to the user even if the user vertically scrolls the page.
The page has a heading at the top of the page which is 75 px tall. Now when the user is at the top of the page and has not scrolled vertically, the DIV must be postioned below the heading. However, once the user scrolls the page causing the heading to go out of sight, the same DIV must now be position at the top of the page (i.e. near the top edge of the browser viewport)
My big concern is the support for window.onscroll event on browsers. I checked QuirksMode for compatibility (http://www.quirksmode.org/dom/events/scroll.html). It seems to have decent compatibility on IE and Firefox. However the Safari and Chrome support seems a bit quirky. And both these browsers are part of my target browsers' list.
Can anybody tell me if the window.onscroll event is an effective way of detecting page/frame scrolls? Any other suggestions?
P.S. I have considered using the CSS position: fixed rule. It is close to the solution but the DIV is just stuck to one position and I cannot have it adaptively move based on the visiblity of the heading.
Thanks!
Here's another alternative method you could try. I use it to position a toolbar div on top of the page (works for ipad too).
Instead of using the onScroll event, I am using a timer to fire every 500ms to detect where the windows is scrolled to via scrollTop . You could adjust the timer to about 200ms if you like.
Here's a stripped down sample of my code:
This jquery code checks when and if my dom element div named "floatlayer" (which is a div that contains my buttons toolbar) is ready and then calls the function setRepeater
$(#floatlayer").ready(function () {
return setRepeater();
});
Then, this is the function that creates a timer to keep executing the function "keepIncrease" every 500ms
function setRepeater() {
aTimer = window.setInterval("keepIncrease()", 500);
return false;
}
This is the function keepIncrease() which is repeated every 500ms and is responsible to position the toolbar div based on the current window scrolled position :
function keepIncrease() {
var divToolbar = $("#floatlayer")[0];
var currentPos = $(window).scrollTop();
divToolbar.style.top = currentPos + "px";
return false;
}
Something else out of topic:
If your content is inside an iframe, you could also use $(window.parent).scrollTop() instead of $(window).scrollTop()
If you read about the clunkiness in WebKit on Quirksmode, you'll notice the following:
Safari (but not on iPhone) and Chrome seem to monitor scrollTop acces in order to determine whether the user has scrolled an element. The log function of my test script changes scrollTop regularly, and Safari responds by firing a scroll event. Since the logging of this event changes the log element's scrollTop once more, scroll events will be fired continuously.
All this happens when the log element at the bottom of the page doesn't have a scrollbar yet, when it has a normal overflow: visible, and even when I set scrollTop to 0 each time a new event is logged. The buggy behaviour stops only when I remove the scrollTop line entirely.
This issue shouldn't affect what you're trying to achieve since you're not setting the scrollTop of any element. You're attaching onscroll to the window, which appears to have no issues between any browser anyway.
Why not just use "fixed"?
Oh, I see, I missed the part about the header.
You could still utilize the position:fixed option, though. You would just set the position against "body" initially (accounting for the 75px gap), and once the header leaves viewability, you can realign the div against the top of the viewport. But without using onscroll in some way or another you probably won't be able to do what you want to do. Sometimes you just have to make the decision: Do I want the feature more, or the people more?

How to scroll to an element in jQuery?

I have done the following code in JavaScript to put focus on the particular element (branch1 is a element),
document.location.href="#branch1";
But as I am also using jQuery in my web app, so I want to do the above code in jQuery. I have tried but don't know why its not working,
$("#branch1").focus();
The above jquery (focus()) code is not working for div, whereas If i am trying the same code with textbox, then its working,
Please tell me, how can I put focus on a div elemnt using jQuery?
Thanks!
For my problem this code worked, I had to navigate to an anchor tag on page load :
$(window).scrollTop($('a#captchaAnchor').position().top);
For that matter you can use this on any element, not just an anchor tag.
Like #user293153 I only just discovered this question and it didn't seem to be answered correctly.
His answer was best. But you can also animate to the element as well.
$('html, body').animate({ scrollTop: $("#some_element").offset().top }, 500);
You can extend jQuery functionalities like this:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 500);
}});
and then:
$('...').scrollToMe();
easy ;-)
Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.
Check out jquery-scrollintoview.
ScrollTo is fine, but oftentimes you just want to make sure a UI element is visible, not necessarily at the top. ScrollTo doesn't help you with this. From scrollintoview's README:
How does this plugin solve the user experience issue
This plugin scrolls a particular element into view similar to browser
built-in functionality (DOM's scrollIntoView() function), but works
differently (and arguably more user friendly):
it only scrolls to element when element is actually out of view; if element is in view (anywhere in visible document area), no scrolling
will be performed;
it scrolls using animation effects; when scrolling is performed users know exactly they're not redirected anywhere, but actually see
that they're simply moved somewhere else within the same page (as well
as in which direction they moved);
there's always the smallest amount of scrolling being applied; when element is above the visible document area it will be scrolled to the
top of visible area; when element is below the visible are it will be
scrolled to the bottom of visible area; this is the most consistent
way of scrolling - when scrolling would always be to top it sometimes
couldn't scroll an element to top when it was close to the bottom of
scrollable container (thus scrolling would be unpredictable);
when element's size exceeds the size of visible document area its top-left corner is the one that will be scrolled to;
Use
$(window).scrollTop()
It'll scroll the window to the item.
var scrollPos = $("#branch1").offset().top;
$(window).scrollTop(scrollPos);
If you're simply trying to scroll to the specified element, you can use the scrollIntoView method of the Element.
Here's an example :
$target.get(0).scrollIntoView();
I think you might be looking for an "anchor" given the example you have.
This link will jump to the anchor named jump
<a name="jump">This is where the link will jump to</a>
The focus jQuery method does something different from what you're trying to achieve.
For the focus() function to work on the element the div needs to have a tabindex attribute. This is probably not done by default on this type of element as it is not an input field. You can add a tabindex for example at -1 to prevent users who use tab to focus on it. If you use a positive tabindex users will be able to use tab to focus on the div element.
Here an example: http://jsfiddle.net/klodder/gFPQL/
However tabindex is not supported in Safari.
maybe you want to try this simple one
$(document).ready(function() {
$(".to-branch1").click(function() {
$('html, body').animate({
scrollTop: $("#branch1").offset().top
}, 1500);
});
});

Scrolling Overflowed DIVs with JavaScript

I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.
So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):
$("#thediv").scrollTop = $("#thediv").scrollHeight;
However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.
The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.
Any ideas guys? This one's got me stumped. Thanks!
scrollHeight should be the total height of content. scrollTop specifies the pixel offset into that content to be displayed at the top of the element's client area.
So you really want (still using jQuery):
$("#thediv").each( function()
{
// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
this.scrollTop = scrollHeight - this.clientHeight;
});
...which will set the scroll offset to the last clientHeight worth of content.
scrollIntoView
The scrollIntoView method scrolls the element into view.
Using a loop to iterate over a jQuery of one element is quite inefficient. When selecting an ID, you can just retrieve the first and unique element of the jQuery using get() or the [] notation.
var div = $("#thediv")[0];
// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(div.scrollHeight, div.clientHeight);
div.scrollTop = scrollHeight - div.clientHeight;
$("#thediv").scrollTop($("#thediv")[0].scrollHeight);
It can be done in plain JS. The trick is to set scrollTop to a value equal or greater than the total height of the element (scrollHeight):
const theDiv = document.querySelector('#thediv');
theDiv.scrollTop = Math.pow(10, 10);
From MDN:
If set to a value greater than the maximum available for the element,
scrollTop settles itself to the maximum value.
While the value of Math.pow(10, 10) did the trick using a too high value like Infintiy or Number.MAX_VALUE will reset scrollTop to 0 (Firefox 66).
I had a div wrapping 3 divs that were floating left, and whose contents were being resized. It helps to turn funky-colored borders/background on for the div-wrapper when you try to resolve this. The problem was that the resized div-content was overflowing outside the div-wrapper (and bled to underneath the area of content below the wrapper).
Resolved by using #Shog9's answer above. As applied to my situation, this was the HTML layout:
<div id="div-wrapper">
<div class="left-div"></div>
<div id="div-content" class="middle-div">
Some short/sweet content that will be elongated by Jquery.
</div>
<div class="right-div"></div>
</div>
This was the my jQuery to resize the div-wrapper:
<script>
$("#div-content").text("a very long string of text that will overflow beyond the width/height of the div-content");
//now I need to resize the div...
var contentHeight = $('#div-content').prop('scrollHeight')
$("#div-wrapper").height(contentHeight);
</script>
To note, $('#div-content').prop('scrollHeight') produces the height that the wrapper needs to resize to. Also I am unaware of any other way to obtain the scrollHeight an actual jQuery function; Neither of $('#div-content').scrollTop() and $('#div-content').height would produce the real content-height values. Hope this helps someone out there!

Categories

Resources