How to 'lock' scroll to div? - javascript

I've set up a scrolling website (essentially a parallax-styled page, without the parallax effects) where each "page" is just a div that takes up 100% of the screen. But I need some sort of mechanism to 'lock' the scroll into the correct position so that the div will align properly with the user's browser.
If you need an example, Flickr's splash page does this perfectly.
Thanks.
EDIT: Here's a link to the site I'm working on. The code's a bit messy, and some images aren't loading (since they're not hosted yet) but it's there to give you a rough idea of how the site functions.
http://fiddle.jshell.net/99QjJ/

I just tried to build a fast solution: Fiddle
It prevents the normal scrolling and scrolls just to the appropriate offset of the divs:
if(!scrolling) {
scrolling = true;
currentDiv = (scrollDirection == "down" ? currentDiv + 1 : currentDiv - 1)
$("html,body").animate({
"scrollTop":offsets[currentDiv]
},{queue:true,duration:1000,complete:function() {
window.setTimeout(function() {
scrolling = false;
},200);
}});
It's no complete solution but I think this would work.
Another idea would be using one of the thousands of jQuery plugins which make the page scrollable via the arrow keys. I think if each of the divs fits the entire screen size there's no actual need for scrolling "in between".

So you're doing a 'one page' site, correct? Can't you use anchor tags on each element you want to jump to?
You can animate it to make it look pretty with this nice jQuery plugin

Related

How to add child nodes to parent nodes without having view jump to where element is being loaded?

As I am rendering elements and appending them to a parent div, my screen keeps jumping to the bottom most element as it is being loaded rather than loading them and having the view stay at the current view. So at the beginning it should be at the top of the screen and stay there instead of jumping to the bottom and as I scroll down and it renders more elements it should stay at that spot as well whilst the rest loads.
Here is the code of what is essentially in my js file.
function loadMultipleElements(amountToLoad, url) {
var parentDiv = document.getElementById("instance");
for(var i = 0; i < amountToLoad; i++) {
var iframe = document.createElement('div')
iframe.innerHTML = '<iframe src=\"' + url + '\"></iframe>';
parentDiv.appendChild(iframe);
}
}
Then how I'm loading it in the html file with infinite scroll from jquery,
<script>
loadMultipleElements(5, "https://www.example.com");
$(window).scroll(function() {
if($(window).scrollTop() == ($(document).height()) - $(window).height()) {
loadMultipleElements(5, "https://www.example.com");
}
});
</script>
So when I run this on my localhost it will have everything render as it opens but jump to the bottom of the screen to render it then jump back to the current view. The big problem here is because of infinite scroll and how it keeps jumping to the bottom it ends up going indefinitely because it keeps jumping to the bottom triggering the jquery function.
EDIT: Plunker included though not sure how to get jquery to do infinite scrolling with plunker at the moment so right now just have a fixed load value of 10. Even already it is scrolling to the bottom as it renders more.
http://plnkr.co/edit/fUrJek3RAicHG98lUrC9?p=preview
Your problem is caused by the fact that when bing automatically focuses the search bar, your browser scrolls down to the iframe so that you can type in text.
(See a "slow-mo illustration" here.)
The only workaround I know of is to use the iframe sandbox attribute - HTML5 only! - to prevent bing from focusing the searchbar. Then when the iframe is finished loading, we reallow JavaScript. Example.
There are, however, a couple of problems with this approach.
Since it works by disabling javascript when the iframe is loading, desired javascript functionality is also disabled. (ie. no 'recent stories')
It feels incredibly hacky.
It isn't obvious what we're trying to do.
PS: Here's what W3Schools has to say about the sandbox attribute and here's a walkthrough on html5rocks.
PPS: If anyone knows of a better way to do this, I'd love to hear it.

jquery animate/scrollTop to multiple anchors inside divs

I'm having a problem implementing relatively complicated auto-scroll functionality on my page. This displays the issue in my code...
http://codepen.io/d3wannabe/pen/XXxdQq
I have multiple divs on my page (blue,red,green in my example) that I not only want to be able to scroll to (which the top 3 buttons in my example achieve perfectly), but I want to be able to scroll WITHIN (which the bottom 3 buttons represent my best attempt at).
The thing I can't figure out, is why the scroll within function works well on my first div ("scrollTo3rdBlueItem" button), but then less accurately with the other divs ("scrollTo3rdRedItem" and "scrollTo3rdGreenItem" buttons). In my full web application (which obviously has more data to scroll through), I basically see that the lower down the page the parent div is positioned, the less accurately I'm able to scroll within it.
I'm struggling to identify much of a pattern though so can't simply try tweaking the offset values. Any ideas what I might be doing wrong here would be hugely appreciated!!
...since I wasn't allowed to post this without quoting code - here's the jquery function you can see in my codepen!
function scrollToParent(parentID){
$('html,body').animate({scrollTop: $('#'+parentID).offset().top}, 500);
}
function scrollToChild(parentID, childID){
//first focus on the parent
scrollToParent(parentID);
$('#'+parentID).animate(
{scrollTop: $('#'+ childID).offset().top - 100}
, 500);
}
UPDATE
Answer here was COMPLETETLY wrong. Left here to preserve the comments.
UPDATE 2
Got IT! You need to take in to account the offset of the parent div. Update your scrollToChild function to the below;
$('#'+parentID).animate(
{
scrollTop: $('#'+ childID).offset().top - $('#'+parentID).offset().top
}, 500);

How to improve JS scroll performance?

I'm working on revamping my website, and the new one can be found on http://beta.namanyayg.com/
There are mainly two things related to scroll on the site:
To check on which 'page' the user is on, by calculating the top offset and scroll position, then adding a class to the page.
To smooth scroll on menu click.
I've written code for both, but there is a lot of lag.
The first one almost always results in lagging. The second one, as a result, lags too. I have included a boolean to check if it's smooth scrolling and disabled the normal scroll events then, but there's not much change.
Do you have any advice on how to improve performance so there is no (or at least, less) lag? Thank you in advance! :)
...Or is it not related to JS at all? I've optimized everything else...
EDIT: Unminified JS at http://beta.namanyayg.com/js/main.js
If you are using underscore, it has an awesome _.debounce function that is excellent for this sort of thing.
To check how much the user has scrolled from the top of the page (i.e. on which 'page' he is at the moment) can be achieved with:
$(window).scroll(function () {
var scrollAmount = $(window).scrollTop(); // in pixels
if(scrollAmount > SOME_AMOUNT)
{
// add required css class
}
});
To scroll smoothly, to some id for example, you could use:
$("html, body").animate({ scrollTop: $("#someID").scrollTop() }, 1000);
These are both jQuery solutions, so you should have jquery library included. There is also a nice jQuery plugin called waypoints that performs these calculations. It might prove useful to you and it has some other nice features and examples.
I have the same problem. I have a scrollable div with thousands of smaller divs. Every time I call scrollTop to get the scroll-position or set it, it sometimes waits at least 1 second.
I read these slides: http://www.slideshare.net/nzakas/high-performance-javascript-2011 (especially slides 138-139) and now I realize that every call to scrollTop, even as a getter, makes javascript relayout the page. This is most likely the cause of delay, but unfortunately I have not found a solution yet, as in a way to call scrollTop without causing relayouts.
Note: I've only been testing on Chrome.
Also read 'Browsers are smart' section of this article: http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
I've found an easy solution to the lag with getting scrollTop, just call it inside a scroll-handler and save the result in a variable.
for example in jQuery:
var scrollPos = 0,
element = $('.class');
element.scroll(function(){
scrollPos = element.scrollTop();
});
For the second problem, setting the scrollTop, I reduced the amount of DOM elements by only showing the visible elements. In your case make sure only the visible page(s) are added to the DOM. when scrolling to the next page, in the scroll handler remove the top one (use jQuery .detach) and append the next one to the DOM.

div container following scroll of screen

I'd like to set up a "backward-compatible" scrolling sidebar on one of my pages.
I have a page containing information about a species of fish which can be extraordinarily long and images to accompany it.
The images are in the right-hand pane at the moment and I'd like them to follow the user as they scroll to the bottom of the page.
I've used the following code with some success:
jQuery().ready(function($) {
var $scrollingDiv = $("#sidebar");
$(window).scroll(function(){
$scrollingDiv
.stop()
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
});
});
But it jumps too far when scrolling down.
(original position)
(scrolled a single mousewheel click)
When you start scrolling down the page, the sidebar appears around half-way down and as such you can only see two of the images.
Once a user scrolls past X point (say 400px), I would like the sidebar to start moving with the page. However, it also needs to go back to its original position when the user reaches the top of the page once more.
Is there a fix that can be applied to this code, or a better way of approaching this?
---------------------------------------------------------------------------------
EDIT: position:fixed Problem
When I try to apply position:fixed as per Josh and David's suggestions (either bit of JS code), this happens:
Here is Firebug's read-out of the CSS styles attached to this element:
You can use a plugin for this, but it’s such a simple task that you might as well do it on your own.
Consider this simple markup:
<div id="content">Content</div>
<div id="sidebar"><div>Sidebar</div></div>
And this would be all the javascript you need:
var el = $('#sidebar'),
pos = el.position().top;
$(window).scroll(function() {
el.toggleClass('fixed', $(this).scrollTop() >= pos);
});
Now, it will add a class to the #sidebar div as soon as the user scroll further than the sidebar is positioned, so all you need now is som CSS. I’m applying the fixed positioning to a child element to avoid layout problems:
#sidebar.fixed > div{position:fixed;}
I put up a really simple demo here: http://jsfiddle.net/QZyH3/
You should try the jQuery code found in this tutorial, which replicates Apple's shopping cart sidebar. It has a working demo and a very small code footprint.
why not use css position: fixed; property? of course if you don't mind the div being not smooth but straightly following your scrollTop. I've found it not working only in IE6-- by today, so using fixed position is a good solution I think, otherwise you just get with window.scrollTop of DOM and assign it to your element's absolute position top

How to make an element slide with the viewport as it scrolls?

I've Googled for this but must be using the wrong keywords.
Basically I want to use the effect that Magento and now Stack Overflow uses. That is, there is an element in a column, and when you scroll down, it sticks to the top of the viewport. And once scrolled up again, it goes back into the normal page flow.
This Ask A Question is a good page for example. Scroll down and watch the "How to Format" element come down (might need to make your viewport smaller if you have a large screen to see the effect).
I've noticed it is setting position: fixed in the CSS. The JavaScript however is obfuscated.
What's the easiest way to achieve this effect? Is there a jQuery plugin available?
Here is an article that should help: http://www.wduffy.co.uk/blog/keep-element-in-view-while-scrolling-using-jquery/comment-page-1/
I noticed google doing this in certain places, like here http://news.google.com/nwshp?hl=en (the left side navigation bar). From what I can tell, they checking the position on the page and then setting the item to a fixed position once the page is scrolled down enough for the element to start scrolling off the screen.
It looks like the other method, using jQuery to set the top margin will allow the element to lag behind and get choppy (if you don't use animation) since the javascript must continue to position the element.
Here is an example in Ext, it would probably help a lot if I didn't have the select in the event handler, but it works.
Ext.fly(document).on("scroll", function(e,t,o){
Ext.select(".pinnable").each(function(el,c,idx){
var y = window.scrollY;
if(!el.hasClass("pinned")){
var ypos = el.getY();
if(y>ypos){
el.addClass("pinned");
el.set({
originalY:ypos
});
}
} else {
var origy = el.getAttribute("originalY");
if(origy && y<origy){
el.removeClass("pinned")
}
}
});
});

Categories