Change position when scrolling until next div? - javascript

The following JavaScript seemed to work pretty well, until I discovered that the height of the div (with id="fixed") was not the same for all pages.
<script>
window.addEventListener("scroll", function() {
if (window.scrollY >= 450) {
document.getElementById('fixed').style.position = 'relative';
}
if (window.scrollY <= 450) {
document.getElementById('fixed').style.position = 'fixed';
}
});
</script>
For this reason I'd like to adjust it in a way that the position of the div would change as soon as it is scrolled into the the next div with id="next-to-fixed".
I saw another post that implemented jQuery for this, but I only want to use simple JavaScript, so if someone can illustrate me with a way to achieve this, that would be great.
Trial:
<script>
window.addEventListener("scroll",function() {
var elm1 = document.getElementById('product-essential');
if(window.scrollY >= elm1.clientHeight) {
document.getElementById('fixed').style.position = 'relative';
}
if(window.scrollY <= elm1.clientHeight) {
document.getElementById('fixed').style.position = 'fixed';
}
}
);
</script>

This is how you can read the height of a div:
var clientHeight = document.getElementById('myDiv').clientHeight;
and from here on use clientHeight.

Related

Change sticky header text depending on distance from top of page

Hi, trying to have the text inside a sticky header change in relation to how far away it is from the top of the page. Supposing I have a single page site, with several distinct did sections each measuring 100vh. The nav links to them via href="#sectionA", "#sectionB", etc.
So if I start on the landing page and scroll down to "sectionA" the header should change to that sections title. Couldn't figure out how to do this using the .href but if that is a preferable way I'm amendable.
Currently have:
function scrollChange(id) {
var winHeight = window.innerHeight;
if (window.scrollBy(winHeight)) {
document.getElementById(title).innerHTML = 'SomethingB';
}
else if (window.scrollBy(winHeight * 2)) {
document.getElementById(title).innerHTML = 'SomethingC';
}
else {
document.getElementById(title).innerHTML = 'somethingA';
}
}
document.addEventListener('scroll', function() {scrollChange();});
The DOM manipulation doesn't matter for right now; just trying to get the correct reference by scroll. No JQuery answers please. Thank you!!
Complete re-write based on feedback and testing :]
function scrollChange(id) {
console.log('scroll w.height:['+ window.innerHeight +'] scroll:['+ window.scrollY +']');
// start with the biggest value first
if (window.scrollY > (window.innerHeight / 2)) {
document.getElementById(id).innerHTML = 'Something big';
} else if (window.scrollY > (window.innerHeight / 3)) {
document.getElementById(id).innerHTML = 'Something middle';
} else {
document.getElementById(id).innerHTML = 'Something small';
}
}
window.addEventListener('scroll',function(){
scrollChange('sticky');
});
<div id="sticky" style="position:fixed;top:0px;line-height:2em;background:#fff">
Sticky title (0)
</div>
<div style="margin-top:3em;line-height:3em">
<p>This</p><p>is</p><p>just</p><p>padding</p><p>to</p>
<p>test</p><p>scrolling</p><p>down</p><p>the</p>
<p>page</p><p>and</p><p>this</p><p>is</p><p>more</p>
<p>padding</p><p>to</p><p>test</p><p>scrolling</p>
<p>down</p><p>the</p><p>page</p>.</div>

How to make an element become fixed when 50px from the top of the screen

I have a html div element that scrolls with the page but I would like it to become fixed once it reaches 50px from the top of the screen...
How is this done?
My div id is #box
Thanks!
-Ina
If you want it to be fixed at the top of the page at some distance from the top, you can check the top offset of the element and change the class when it reach the distance you want.
Here is the jquery code for your reference
jQuery(document).scroll(function() {
var documentTop = jQuery(document).scrollTop();
console.log('this is current top of your document' + documentTop );
//box top is 891
if (documentTop > 841) {
//change the value of the css at this point
jQuery("#box").addClass("stayfix");
}
else
{
jQuery("#box").removeClass("stayfix");
}
});
You need to be more specific about what have you done so far. For eg, how did you make the div element to scrolls inside the page. using css or js/jquery animation features?That will help us to give more specific answer.
**Edited According to your fiddle.
They are right, this question is duplicate. Here is a code I made with answers from the forum.
var box_top = $("#box").offset().top;
$(window).scroll(function (event) {
if ($(window).scrollTop() >= (box_top - 50)) {
$("#box").css({position:"fixed",top:"50px"});
} else {
$("#box").css({position:"relative"});
}
});
Hope it helps anyway.
https://jsfiddle.net/ay54msd5/1/
Try something like this. It's a solution using jquery (hopefully not a problem) that checks the scrollHeight of the page every time the page scrolls. If the scrollHeight is greater than a certain threshold, the element becomes fixed. If not, the element is positioned relatively (but you can do whatever you want in that case.
$(document).ready(function() {
var navFixed = false;
var $box = $("#box");
var topHeight = 50;
$(document).scroll(function() {
if ($(document).scrollTop() >= topHeight && !navFixed) {
$box.css("position", "fixed");
navFixed = true;
}
else if ($(document).scrollTop() < topHeight && navFixed) {
$box.css("position", "relative");
navFixed = false;
}
});
});
You would have to write some additional CSS targeting the #box element that tells it what coordinates you'd like it to be fixed to.

document.body.scrollTop value stuck at 0

I have a bit of text that I want to change when the user scrolls a certain distance. However, when I scroll, the value of document.body.scrollTop remains at 0.
var scroll = document.body.scrollTop;
if (scroll < 50) {
document.write("A");
} else {
document.write("B");
}
When checking the log, the value of scroll never budges from 0, thus the text never switches from A to B when scrolling. Thanks for any help in advance.
EDIT: None of the first three answers seem to work for me. I suppose I should provide some context.
Building my design portfolio site. View the early build here. I'd like to be able to change the word "designer" in the banner to other descriptor words as the user scrolls down the page, but can't seem to be able to listen to the current scroll location.
Why are you placing that script inline within the banner? Why not implement your logic within your existing $(window).scroll(function () { as that event seems to be setting the opacity correctly on scroll.
Just add:
if(scrollTop < 50){
$('#banner h1').text("My name is John. I'm a designer");
} else {
$('#banner h1').text("My name is John. I'm a thinker");
}
Live Demo
if(document.attachEvent){
document.attachEvent('onscroll', scrollEvent);
}else if(document.addEventListener){
document.addEventListener('scroll', scrollEvent, false);
}
function scrollEvent(e){
var scroll = document.body.scrollTop;
var text = null;
if (scroll < 50) {
text = document.createTextNode('A');
} else {
text = document.createTextNode('B');
}
document.body.appendChild(text);
}
Though unrelated to your issue, you should stay away from document.write whenever you can. See Why is document.write considered a "bad practice"? for more detail.
this should do it. "document.documentElement.scrollTop" is an IE variant.
should work cross browsers.
window.onscroll = function() {
var scroll = window.scrollY || document.documentElement.scrollTop;
if (scroll < 50) {
document.write("A");
} else {
document.write("B");
}
}
DEMO FIDDLE
var el = $('.test');
//alert(el.scrollTop());
el.on('scroll', function(){
if(el.scrollTop()>50){
alert(el.scrollTop());
}
});
Try this.

Change margin top of div based on window scroll

I have a bar at the top of my page that is position fixed. When the user scrolls to a certain point I want the bar to start moving up as if it was relatively or absolutely positioned.
Right now the css of the bar changes from fixed to absolutely positioned but of course this sets the div straight to the top of the page.
I have been looking at this for ages and cannot get my head around how I would push the bar up one pixel at a time for every pixel scrolled past the _triggerOffset
Can anyone enlighten me?
function banner(){
var _barOffset = $('#top-bar').outerHeight(),
_navOffset = $('#navigation').offset().top,
_triggerOffset = _navOffset-_barOffset;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if (_scroll >= _triggerOffset) {
$('#top-bar').css({'position':'absolute'});
}
});
}
banner();
I have done a fiddle.
Check this fiddle
Working Demo
$(document).ready(function() {
var postionToTriggerMove = 500;
var positioninitial = $(window).scrollTop();
var positioninitialLine = $(".line").offset().top;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if(_scroll > positioninitial) {
if(_scroll >= (postionToTriggerMove - 5) && _scroll <= (postionToTriggerMove + 5) )
{
var topBarPostion = $(".line").offset().top;
$('.line').css({'position':'absolute',"top":topBarPostion});
}
}
else {
if(_scroll >= (postionToTriggerMove - 5) && _scroll <= (postionToTriggerMove + 5) )
{
var topBarPostion = $(".line").offset().top;
$('.line').css({'position':'fixed',"top":positioninitialLine});
}
}
positioninitial = _scroll;
});
});
You could try something like the below:
function banner(){
var _barOffset = $('#top-bar').outerHeight(),
_navOffset = $('#navigation').offset().top,
_triggerOffset = _navOffset-_barOffset;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if (_scroll >= _triggerOffset) {
$('#top-bar').css({'position':'absolute','top':_triggerOffset - (_scroll-_triggerOffset)});
}
});
}
banner();
This code is highly untested, however what we are doing is initially setting the element to an absolute position and defining the top of this element as the _triggerOffset, then we take the difference between the current scroll and the triggerOffset and subtract this from the top position to make the bar move up the more you scroll down.
Not sure if that's what you had in mind, but I'd look at a solution like this. You might want to add some conditions in there to ensure that top never goes below 0 or the nav will go off the screen.
Thanks, had a play around with both examples and they worked pretty good.
In the end I tweaked my code and instead of making the bar position top 0px I made it position top with the pixels equal to the offset distance. Don't know why I didn't think of this before.
On another note I am using Shinov's code for anoher project as I quite like it :)
Thanks
function banner(){
var _barOffset = $('#top-bar').outerHeight(),
_navOffset = $('#navigation').offset().top,
_triggerOffset = _navOffset-_barOffset;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if (_scroll >= _triggerOffset) {
$('#top-bar').css({'position':'absolute', 'top':_triggerOffset+'px'});
}else if (_scroll <= _triggerOffset){
$('#top-bar').css({'position':'fixed', 'top':'0px'});
}
});
}

javascript scroll to bottom of div class

Hi I am trying to implement a simple chatbox in django and was wondering how to scroll to the bottom of a div class using javascript? Basically when the page loads I would like so that users can see the most recent message sent to them instead of the least recent.
I had to do this recently for a similar thing. I found a basic jquery plug-in that will smoothly scroll an element onto the screen.
(function($) {
$.fn.scrollMinimal = function() {
var cTop = this.offset().top;
var cHeight = this.outerHeight(true);
var windowTop = $(window).scrollTop();
var visibleHeight = $(window).height();
if (cTop < windowTop) {
$('body').animate({'scrollTop': cTop}, 'slow', 'swing');
} else if (cTop + cHeight > windowTop + visibleHeight) {
$(jQuery.browser.webkit ? "body": "html")
.animate({'scrollTop': cTop - visibleHeight + cHeight}, 'slow', 'swing');
}
};
}(jQuery));
which is used like this:
$('#chat').scrollMinimal();
Well, the basic script is set the scrollTop equal to scrollHeight, so you need a script like this:
var DIV = document.getElementById('theDIVElement');
DIV.scrollTop = DIV.scrollHeight;
You only need to change theDIVElement to your DIV id.
This is the script I used in my chat:
<SCRIPT LANGUAGE="JavaScript">
<!--
function myScroll() {
window.scrollBy(0,01)
setTimeout('myScroll()',100); }
if (document.layers || document.all)
myScroll()
//--></SCRIPT>
This is also nice for when new messages are added, if you scroll to the bottom too fast, it's hard on your eyes while you're trying to read.

Categories

Resources