jquery: how to scroll a div by n pixels - javascript

Using jQuery, how do you scroll a div by N more pixels?
So far I tried
$("div.foo").scrollTop(75); //scroll down by 75 pixels

From the jQuery docs for scrollTop:
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.
The version of the function you are calling sets the vertical position of the scroll bar from the top of the element, not from the current position. So in order to scroll down from the current position you first have to retrieve your current position. There are a few ways to do that, but you could do something like:
var $foo = $("div.foo");
$foo.scrollTop($foo.scrollTop() + 75); // scroll 75px down from current

If you are looking for Vanilla JavaScript solution like I was, here it is.
const selectedElement = document.querySelector('div.foo');
selectedElement.scrollTop = 75;
querySelector documentation,
scrollTop documentation

the following code may help and you may see this link .
and you can pixel value from window atrributes.Thank you.
var d = $('#div1');
d.scrollTop(d.prop("scrollHeight"));

Related

Fake position Fixed inside a Div but relative to window top, while scrolling

I had to fake a fixed position of a div inside its container but relative to window by giving it an absolute position and giving it the top value in with jquery's scrollTop(). So far it seems like a decent solution but the fixed effect only work in Chrome. In firefox and ie10 it moves slowly and ie9 it do something like vibrate
if ($.browser.webkit) {
//First I had to do some hack in order to get the scrollTop() same return in all browsers
var bodyPos = $('body').scrollTop();
}else{
var bodyPos = $('html, body').scrollTop();
}
//then I can calculate the point relative to the top of the window
var pos1 = $('#four').position().top;
var imgPos = bodyPos - pos1
$('#fixed1').css({'top': imgPos})
Anybody knows how to make this effect crossbrowser?
Thanks
I've finally fixed, as you see in this case I wanted to make a fake fixed position of an image inside it's container while scrolling.
Well, Occam's Razor:
I created a container for the image and give it an absolute position width height 100% and top 0.
Then I set the image as background of the container with fixed attachment "et voilĂ " the job is done.
Sometimes this kind of things happen :)

How do I move the background image of a DIV based on the scrollbar movement?

I have been looking into parallax effects for vertical scrolling on my web page, and after some research, I'm not sure that what I want to do is technically a parallax effect.
From what I've seen, most parallax effects assume you want to be able to scroll indefinitely with many background images rolling by, or with huge images that repeat.
What I want to do is have the background of two DIVs be filled with a background image as the scroll bar reaches the bottom of the page. Note that I do not want the background images to stretch. I'm assuming to get the effect I want that these images would have a vertical height bigger than most people's viewport, and then their vertical position would change. When the user's scrollbar is at the top, a certain amount of the background is visible, and then it moves vertically to fill the background space as the user scrolls down.
Please see the image below for a visual explanation of the effect I hope to acheive:
The height of the veiwport will vary depending on the length of content inside the inner DIV.
My trouble is that if what I am trying to do is not exactly a parallax effect, then I don't know what else to call it, and my attempts to search by describing it keep landing me back at pages offering tutorials on parallax effects. So I've been stumped by a lack of terminology.
If someone could direct me to how I can control the vertical position of the background depending on the scrollbar position, that would be much appreciated. If this can be done with just CSS that would be great, but I'm assuming some Javascript would be required. A jQuery solution would also work for me.
Update:
After searching using the terms provided in comments, I've got the background image in the outer DIV to almost do what I want with the following code:
$(window).scroll(function () {
var yPos = $("#outerDiv").height() - ($("#outerDIV").height() * ($(window).scrollTop() / $(window).height()));
document.getElementById('outerDIV').style.backgroundPosition="0px " + yPos + "px";
});
It moves the background image in the right direction relative to the scrolling, but what it lacks is constraining that motion to within the viewport. Getting the right proportions based on the viewport and DIV sizes is proving to be just a little beyond my mathematical abilities.
For your requirement, you have to use a jquery parallax plugin to guide this activity, my best suggest it to use a Superscollorama and play with the elements as your wish...
As far as your question, Try this example,
controller.addTween(
'#examples-background',
(new TimelineLite())
.append([
TweenMax.fromTo($('#parallax-it-left'), 1,
{css:{backgroundPosition:"(0 -54px)"}, immediateRender:true},
{css:{backgroundPosition:"(0 -54px)"}}),
TweenMax.fromTo($('#parallax-it-right'), 1,
{css:{backgroundPosition:"(0 -54px)"}, immediateRender:true},
{css:{backgroundPosition:"(0 54px)"}})
]),
1000 // scroll duration of tween
);
You serial vice change as far as your wish...
Try practice this plugin, hope that works for you...
http://johnpolacek.github.io/superscrollorama/
Thanks...
Turns out what I want to acheive is possible with no special plugins, just some carefully thought out math. I did use a little jQuery syntax, but I don't think it's strictly necessary.
The code below has copious notes, so hopefully it's largely explanatory. In summary, you just need to find the position of the background image when the scroll would be at the top, and the position it would be if the scroll bar was at the bottom, and then you can use the percentage of the scrollbar's movement to work out where you are between those two points. It's a little tricker than just that, of course, in that you have to account for the difference between the total height of the scroll bar and where your DIV appears on the page and a few other adjustments, but the details of what I did are below.
What I've done here is just for the "outer DIV" that I described in my question. To get a background to move like the "inner DIV" I described, you'd have to modify the code, presumeably by reversing a few parameters. I haven't done that yet, but it seems like a straightforward task.
Hope others find this code useful. If anyone has suggestions on how it can be made more efficient or better, please let me know.
function moveBG(){
// imageHeight is not the total height of the image,
// it's the vertical amount you want to ensure remains visible no matter what.
var imageHeight = 300;
// Get the maximum amount within the DIV that the BG can move vertically.
var maxYPos = $("#outerDIV").height() - imageHeight;
// Get the amount of vertical distance from the top of the document to
// to the top of the DIV.
var headerHeight = document.getElementById("outerDIV").offsetTop;
// Calculate the BG Y position for when the scrollbar is at the very top.
var bgTopPos = $(window).height() - headerHeight - imageHeight;
// I don't want the image to wander outside of the DIV, so ensure it never
// goes below zero.
if (bgTopPos < 0)
{
bgTopPos = 0;
}
// Calculate the BG Y position when the scrollbar is at the very top.
var bgBottomPos = $(document).height() - $(window).height() - headerHeight;
// To prevent the BG image from getting cut off at the top, make sure
// its position never exceeds the maximum distance from the top of the DIV.
if (bgBottomPos > maxYPos)
{
bgBottomPos = maxYPos;
}
// Subtract the top position from the bottom, and you have the spread
// the BG will travel.
var totalYSpan = bgBottomPos - bgTopPos;
// Get the scrollbar position as a "percentage". Note I simply left it as a
// value between 0 and 1 instead of converting to a "true" percentage between
// 0 and 100, 'cause we don't need that in this situation.
var scrollPercent = ($(window).scrollTop() / ( $(document).height() - $(window).height()));
// The percentage of spread is added to the top position, and voila!
// You have your Y position for the BG image.
var bgYPos = bgTopPos + (Math.round(totalYSpan * scrollPercent));
// Apply it to the DIV.
document.getElementById('outerDIV').style.backgroundPosition="0px " + bgYPos + "px";
}
// Place the BG image correctly when opening the page.
$(document).ready(function() {
moveBG();
});
// Make it update when the scrollbar moves.
$(window).scroll(function () {
moveBG();
});

JQuery Offset and ScrollTop Problems

I'm trying to fix a elements position based on the scroll position within the window.
I thought it would be as easy as getting the offset of the element where the fixed element should become fixed and then when the window.scrollTop is equal to it add CSS but it is weird.
It seems as though the offset of the element is larger than the scrollTop largest numeral.
Is there any other way of getting this to work?
I want it to have the same functionality as this with regards to the footer on scroll;
http://be.blackberry.com/
But I don't want to clone the element, I want to detect when it gets to near the bottom of the page and then change the position on the bottom of the element.
Thanks in advance.
B
This should help get you in the right direction:
var footer = $("#footer");
// min amount to show when not scrolled to the bottom of the page.
var minVisable = 25;
$(parent.document).scroll(function() {
// check position
if (window.scrollY + window.innerHeight + minVisable > $("html").height()) {
// if at the bottom of the page, stick the footer to it
footer.css("position","absolute").css("top", $("html").height() - footer.height());
} else {
// else keep top part of footer on the screen
footer.css("position","fixed").css("top", window.innerHeight - minVisable );
}
});

Changing div postion depending on page scroll

I have the following code below that changes a div's position to fixed once an element scrollTop is greater than a number. I am trying to either amend this script or find a different solution so that the div will scroll between a range and STOP scrolling at some point ( so the div doesn't go off the page or overlap with footer elements.
I don't know if the right way is to say that IF scrollTop is greater than 150 then position=fixed, and if it's greater than 600 then position goes back to absolute, or if there's a better way, like distance from the bottom...
AND I use MooTools, not jQuery. I know there are a few jQuery options / plugins that do this. Thanks in advance!
window.onscroll = function()
{
if( window.XMLHttpRequest ) { // IE 6 doesnt implement position fixed nicely...
if (document.documentElement.scrollTop > 150) {
$('tabber').style.position = 'fixed';
$('tabber').style.top = '0';
} else {
$('tabber').style.position = 'absolute';
$('tabber').style.top = 'auto';
}
}
}
the script above is wrong on many levels.
don't use window.onscroll but window.addEvent("scroll", function() {});
cache selectors. using $("tabber") 3 times on each scroll when the element does not change is expensive.
just do var tabber = $("tabber") and reference that.
you don't need to do
$("tabber").style.position = ...
$("tabber").style.top = ...
do:
tabber.setStyles({
position: "fixed",
top: 12123,
right: 24
});
There are mootools plugins for this, eg scrollSpy by David Walsh: http://davidwalsh.name/mootools-scrollspy
it can allow you to set scripted events upon reaching various scrolling destinations or events, look at the examples.
or you could just write it yourself, eg, this took me 15 mins to do:
http://jsfiddle.net/dimitar/u9J2X/ (watch http://jsfiddle.net/dimitar/u9J2X/show/) - it stops being fixed when it reaches to 20 px of the footer. and then goes back to fixed if scrolling up again.

Chat scroll bar

I'm working on my chat box, when new posts are added to the bottom, how could I make the scroll bar follow new data at the bottom as its added, or stay where you are if say your in the middle rereading something, kinda like most irc clients do?
Make it scroll to it's scrollheight:
var el = document.getElementById("theDiv");
el.scrollTop = el.scrollHeight;
When a new message is received first check if the current scroll position is equal to the scrollHeight (or possibly within a small percentage of the scrollHeight, for cases where a user hasn't quite scrolled to the bottom but this is imperceptible).
If it is then simply add the message and set the scrollTop = scrollHeight;
If not then leave it alone.
You can modify the element's scrollTop property. Whenever you want to set it to the bottom you can just set it to some big number (one that couldn't conceivably be smaller than the height):
element.scrollTop = 100000;

Categories