div container following scroll of screen - javascript

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

Related

Html, css, and jQuery. Something isnt working in my code

I'm new to jQuery and watching a tutorial for a sticky nav bar and something went wrong and idk what to do!
In my Script file I have it so it runs this code on load [http://pastebin.com/XYWR5tKJ][1] and I have a class in css to use with the nav Placeholder wrap.
Well the margin property doesn't seem to be working, if you run the site and scroll the whole way down the nav bar sticks to the side, its supposed to be centered(the margins job). I have no idea why its not doing it, its probably something stupid but please help!`
HERES THE CODE__
Script.js: http://pastebin.com/XYWR5tKJ
Css: http://pastebin.com/Y51rYJVE
HTML: http://pastebin.com/tTftEJKh
__
THANKS!
[1]: http://pastebin.com/tTftEJKh
Basic set up for a fixed, centered element is:
Containing element that is position fixed.
An element within that has margin:0 auto; and a set width.
I'd say that your left:0 inside fixed is counteracting things mostly.
Since you didn't specify responsive is this good enough for you?
http://jsbin.com/nevuqi/4/
Also probably better, as a tip to share code in something like a JSFiddle, Codepen or JSBin to name a few... good for learning inside of too.
This question reminded me of a JSFIDLE I made a while back to learn the same concept. I've updated it with comments to make it more readable...
It doesn't really answer your question but I thought it would help understand the various components involved when implementing the sticky nav effect in JQuery for anyone who comes across this thread who is unsure.
JavaScript/JQuery code:
(refer to jsfiddle for the accompanying html/css )
//window - the container that holds and renders the document.
//document - the rendered html within the window. the document can be bigger than the window as with this example as scrolling is needed..
//refer to css for more info on the appended classes to nav bar and proceeding element.
$(document).ready(function () {
//add a scroll function to the document that
$(document).on('scroll', function () {
//get the number of pixels that the window is from the top of the document. this is zero at first.
var scrollTop = $(this).scrollTop();
//insert the name of your sticky nav element here in place of .scrollFixed
$('.scrollFixed').each(function () {
//scrollFix variable is initialized as .scrollFixed object with all its attributes.
var scrollFix = $(this);
//gets offset of sticky nav element in pixels
var topDistance = scrollFix.offset().top;
var previousElement = scrollFix.prev();
//this is just for debugging and learning purposes.
$('.fixed_info').html('nav bar is ' + topDistance + ' pixels from top of document');
//if you put topDistance here instead of the number manually, the nav bar will flicker.
//unsure why..
//checks to see whether nav element has been scrolled past the top of window.
if ((298) < scrollTop) {
//make sticky nav a fixed element
scrollFix.addClass("stuck");
//extend the element below for this example so proceeding elements don't visually jump up
//when closing the empty gap.
$(".element_below_fixed_nav_bar").addClass("extend");
//indicates element is fixed!
scrollFix.html("Element now fixed!");
//you will have to manually put the topDistance here as well...
//this checks whether the nav element's original top has passed the top of
//the enclosing window.
//it needs to become scrollable again
} else if (298 >= scrollTop && scrollFix.hasClass('stuck')) {
//make sticky nav a scrollable element
scrollFix.removeClass('stuck');
//make proceeding element shorter to compensate for sticky nav pushing elements below it down.
$(".element_below_fixed_nav_bar").removeClass("extend");
//indicates element is scrollable!
scrollFix.html("Element now moveable!");
}
});
});
});
It's very similar to the logic behind the JavaScript code you linked.
find number of pixels of window from top of document. starts at 0 when document first loads unless otherwise coded. This updates every time you scroll.
find (offset) number of pixels of nav bar element from top of document.
check if nav bar has reached the top of the window by checking its offset to the window. If it is then make it fixed.
check whether the nav bar's original offset has fallen below the top of the window. If it has then make the nav bar scrollable.
It doesn't really answer your question but I thought it would help understand the various components involved when implementing the sticky nav effect in JQuery for anyone who comes across this thread who is unsure.

How to 'lock' scroll to div?

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

HTML fixed large element

I've been racking my brain and my Google Fu for a few hours now trying to find a solution to this one, but can't seem to come up with anything satisfactory.
I want to affix an element to the side of the page for some search criteria, much like Bootstrap's "Affix" plugin. (Demo Here). The problem is that it's going to be very common that the element is much taller than the window. So there will be scrolling of the element itself involved.
Usually this wouldn't be a problem because as the user hits the top + bottom of the document they would be able to see the top and bottom of the fixed element. (See bootstrap example while shrinking you're window very short). But we're planning on using infinite scroll on our results set, meaning there won't be a bottom to hit, and therefore they'll never see the bottom of the fixed element. As the user scrolls down, it needs to be bottom fixed so the user sees all criteria, then on the way up, it needs to be top fixed.
So I started off by modifying Bootstrap's plugin (I'm not actually using bootstrap). Now scrolling down the page is easy, using a fixed point on the bottom of the element means that it's not affixed until you reach the bottom of it.
But scrolling back up again is where I'm hitting issues.
Am I missing something really obvious and easy here (it is Monday morning after all), or does anyone know of a plugin / patch to bootstraps affix.
TL;DR
Need to affix a very tall element to the page and allow it to scroll. So it's fixed on the way down, then as they scroll back up, the element isn't fixed so it's also being scrolled up. Once the top of the element is hit, fix it there.
Is this what you Want to do DEMO
Simple jQuery function that will help.
$(function()
{
affix= $(".affix-top");
var affixHeight = parseInt(affix.height());
var affixTop = parseInt(affix.offset().top);
var affixBottom = parseInt(affixTop + affixHeight);
// Bind a scroll event for the whole page
$(document).bind("scroll", function(e)
{
// Calculate how far down the user has scrolled
var screenBottom = parseInt($(window).height() +$(window).scrollTop() );
// Test if the div has been revealed
if(screenBottom > affixBottom)
{
affix.attr("style","");
affix.css({"bottom":"0px","position":"fixed"});
}
else
{
affix.attr("style","");
affix.css({"top":"0px","position":"relative"});
}
});
});

DIV move up when scrolling down

I've been trying to get a DIV to move up when using the scroll on browser to move down, but I can't find a solution which works.
More specifically, for example if I fill a DIV with images, I want these images to scroll upwards when I scroll the browser window scrollbar downwards. So as you move longer down the page, the DIV moves upwards and shows more images.
Could you give me some suggestions how to receive such an effect?
Try something like this:
$(window).scroll(function(){
$("#scrollingDiv").stop().animate({ "marginTop": ($(window).scrollTop() + 30) + "px"}, "slow");
});
I don't entirely follow what you are trying to do with the <div> content, but there is an easy way to detect page scrolling with jQuery:
$.scroll(function() {
alert('Scroll position: ' + $('html').scrollTop());
});
From there, you can position whatever you want, however you want, using this value $('html').scrollTop().
Maybe I'm misunderstanding but, are you trying to keep your DIV in a fixed position regardless of how far the user scrolls down the page?
If so there's a style for that:
position:fixed

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