div stay fixed at a certain point onscroll - javascript

There is a div, style fixed 60px from top. I want when I scroll down and the distance of div from top reached 10px, the div stop there for the rest of scrolling also when I scroll up it goes back to the old style 60px from top. I did a lot of search but I did not found anything like this. But there is a code which calculate distance from top:
var scrollTop = $(window).scrollTop(),
elementOffset = $('#my-element').offset().top,
distance = (elementOffset - scrollTop);

Here's one way to do it using pure javascript. You can replace some of the selectors like document.getElementById with jQuery selectors like $("id") if you like.
window.onscroll = function(){
var el = document.getElementById('sticky'),
s = window.pageYOffset || document.documentElement.scrollTop, // how much page is scrolled
t = document.getElementById('main').getBoundingClientRect().top; // top of main div
if(s > t){
el.style.position = 'fixed'; //make position fixed instead of absolute
}else{
el.style.position = ''; //clear styles if back to original position
}
}
body {
min-height: 200em;
margin: 0;
padding: 0;
}
header {
background: black;
color: white;
padding: .5em;
}
#main { position: relative; } /* important so the sticky box positions relative to this */
#sticky {
background: cornflowerblue;
padding: .5em;
position: absolute;
right: 1em;
top: 1em;
width: 10em;
color: white;
}
<header>This is just a page header or toolbar.</header>
<section id="main">
<div id="sticky">This should stick to the top when scrolled.</div>
</section>

Here's a jQuery solution. If we're more than 10px from the top of the page add a is-sticky class to the element which you can then style with CSS.
// store the element in a variable
var element = $('.item'),
visible = false;
// on scroll
$(window).scroll(function() {
/**
* store the scroll distance in px
* from the top of the viewport
*/
var scroll = $(window).scrollTop();
/**
* if the scroll is greater than or equal
* to 10px add a class of .is-sticky to the element
* otherwise we're less than 10px from the top
* of the document and therefore don't want
* the element to have the .is-sticky class
*/
if(scroll >= 10) {
if(!visible) {
element.addClass('is-sticky');
visible = true;
}
} else {
if(visible) {
element.removeClass('is-sticky');
visible = false;
}
}
});

Related

Move buttons up when scrolling to footer

I'm trying to push up two buttons vertically displayed in order to put them above the footer content when I'm scrolling to it.
My two buttons are like this:
And I want them to be like that:
Any ways to make it with Javascript?
Thanks a lot !
Since you provided no code at all, here's my solution based on the assumption your buttons are in a parent div and that div has position: fixed and a right / bottom -property set to a certain amount of pixel.
window.onscroll = function (ev) {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2) {
document.getElementById("buttons").style.bottom = "100px";
} else {
document.getElementById("buttons").style.bottom = "20px";
}
}
/*
window.onscroll = function (ev) {
let footerHeight = document.getElementsByTagName("footer")[0].offsetHeight;
if ((window.innerHeight + window.pageYOffset) >= (document.body.offsetHeight - footerHeight)) {
document.getElementById("buttons").style.bottom = "100px";
} else {
document.getElementById("buttons").style.bottom = "20px";
}
}
*/
main {
height: 1000px;
}
#buttons {
position: fixed;
bottom: 20px;
right: 20px;
}
button {
background-color: grey;
border-radius: 50%;
display: block;
border: none;
padding: 15px;
margin-top: 10px;
}
<main></main>
<div id="buttons">
<button></button>
<button></button>
</div>
window.onscroll fires of at every scroll-event. It then checks, if the height of the window (window.innerHeight) and the distance scrolled so far (window.pageYOffset) are greater or equal to the total height of the body (document.body.offsetHeight)(- 2) is added because of an annoying mac-'feature'. For more look at this post). If thats the case, it moves the buttons up 100px instead of the 20px normally. If you dont add the else-statement, your buttons will stay at the position even if you scroll up again.
You can now get a bit creative. If you dont want to hit rock bottom of the page to make the buttons move, change the - 2. So you check for the height of your footer, and substract it from the total body height. Your buttons then start to move once the footer is it. Example of that in the javascript snippet, the part that is commented out.

jQuery/CSS - Add fixed to element on scroll and remove it when reach end of element

Here is the code that i have so far:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 120) {
$("#FixedBox").addClass("fixed");
} else {
$("#FixedBox").removeClass("fixed");
}
});
With this code when the page is scrolled with 120px it add the class fixed to the element with id FixedBox.
What i want?
The element with id FixedBox is contained in element with id Content. So when the page is scrolled with 120 px my script attaches fixed class to FixedBox which makes it fixed.
How can i remove that fixed class when FixedBox reaches the end of Content ?
Here is an image in example:
How i can achieve that?
I hope you can help me!
You could make a function which checks if the scroll height is in between the start and the end of the content and adds the class accordingly. This would even work if you have several blocks of content.
Live Demo (3rd content box is the target)
HTML
<div class="content">
<div class="box">
</div>
</div>
<div class="content" id="target">
<div class="box">
</div>
</div>
CSS
.content{
width: 100%;
height: 400px;
background: red;
margin-bottom: 20px;
position: relative;
}
.fixed{
width: 100px;
height: 100px;
position: fixed;
right: 10px;
top: 10px;
background: blue;
display: block;
}
jQuery
var content = $('#target');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var offset = content.offset();
var height = content.height();
if (offset.top <= scroll && scroll <= offset.top + height) {
$('.box', content).addClass("fixed");
} else {
$('.box', content).removeClass('fixed');
}
});
You can find the end of your content by finding its position by $('#content').offset() or $('#footer').offset() more in the jQuery API Docs.
When you calculate the height of your elements and positions you can figure out the top threshold where you need to remove the fixed class of the FixedBox. Keep in mind that you also need to alter the non-fixed position of your FixedBox when it returns to the DOM flow, else it will snap back to the starting position.
`
var maxScroll = 120 + document.getElementById('#content').offsetHeight;
if (scroll >= 120 && scroll <= maxScroll) {
$("#FixedBox").addClass("fixed");
} else {
$("#FixedBox").removeClass("fixed");
}
You just need to get #content height.

How to make a div stick to top when it reaches the top of the window

How do I make #headnav stick to the top when the page's scroll position reaches the top, then unstick when it would be returned to its original position?
P.S. The repeated "CONTENT" in the code is to simulate scrolling. It is not a spam
jsFiddle
<h1>I AM A HEADER</h1>
<div id="headnav"></div>
<pre><h1>
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
</h1></pre>
body {
margin:0
}
#headnav {
height: 75px;
width: 100%;
background-color: black;
}
This is a very simple thing to do.
Find out what the original position of the header is, then attach a scroll handler to the body which checks the scroll position against the original position of the div.
If the scroll position is greater than the original position, add position: fixed
If the scroll position is less than the original position, remove position: fixed
(Demo)
var headnav = document.getElementById('headnav');
var headnavPos = headnav.offsetTop;
window.onscroll = function() {
if(document.body.scrollTop > headnavPos) {
if(headnav.style.position !== 'fixed') {
headnav.style.position = 'fixed';
}
} else {
if(headnav.style.position === 'fixed') {
headnav.style.position = '';
}
}
}
Just give position: fixed to h1:
h1 {position: fixed; top: 0;}
Fiddle: http://jsfiddle.net/5z4paLgr/1/
i am not sure that understand u correctly but may be this help you
Fiddle http://jsfiddle.net/jg4kdfqs/1/
JavaScript
$(document).ready(function(){
var HeaderTop = $('#header').offset().top;
var hh =HeaderTop + 300;
$(window).scroll(function(){
if( $(window).scrollTop() > HeaderTop ) {
if($(window).scrollTop() > hh) {
$('#header').css({position: 'fixed', top: '0px', background:'#000'});
} else{
$('#header').css({position: 'fixed', top: '0px'});
}
} else {
$('#header').css({position: 'static',background:'red'});
}
});
});
HTML
<div id="header">
nav
</div>
Similar to tarasikgoga but purely javascript:
Fiddle http://jsfiddle.net/5z4paLgr/3/
Javascript
var attached = false;
window.onscroll = function (e) {
if(!attached && window.scrollY > 150){
attached = true;
document.getElementById("headnav").classList.add('fixed-top');
document.getElementById("content").classList.add('content-margin-top');
}
if(attached && window.scrollY < 150){
attached = false;
document.getElementById("headnav").classList.remove('fixed-top');
document.getElementById("content").classList.remove('content-margin-top');
}
}
CSS
body {
margin:0
}
h1{
height: 150px;
margin: 0;
}
#headnav {
height: 75px;
width: 100%;
background-color: black;
}
#headnav.fixed-top{
position: fixed;
top: 0;
}
.content-margin-top{
margin-top: 75px;
}
HTML
Just add id="content" to your content div
Adjust with yours heights (here you have 150px for header and 75px for menu)

Make Div "catch" top of page when scrolling

I have a header on a website that is fixed 20px from the top of the page.
However, I want this to catch the top of the page when scrolling and become fixed to the top of the screen once the user has scrolled that 20px down.
CSS
#header{
padding: 0px 0px 0px 0px;
background: url(../images/header-fill2.jpg) repeat-x top;
position: fixed;
height: 60px;
width: 100%;
top: 20px;
z-index: 5000;
}
I imagine some form of JavaScript is required but have little to no JavaScript experience, so any help would be greatly appreciated.
Just listen for the scroll event and read the value of $(window).scrollTop() and set the top according to that.
Something like:
$(window).on('scroll', function() {
$('#header').css('top', $(window).scrollTop() > 20 ? '0px' : '20px');
});
Example on jsFiddle
The scroll event tells you when the window scrolls. Then, use the scrollTop to find out how much closer to 0 to go:
$(window).on("scroll", function() {
$("#header").css("top", Math.max(0, 20 - $(window).scrollTop()));
});
Live Example
Or to avoid constantly re-creating objects:
(function() {
var $wnd = $(window),
$header = $("#header");
$wnd.on("scroll", function() {
$header.css("top", Math.max(0, 20 - $wnd.scrollTop()));
});
})();
Live Example
Thats how I do that with jQuery.
The position is also cached, for performance reasons:
Here is a fiddle:
http://jsfiddle.net/StephanWagner/u3yrS/
$(document).ready(function() {
var cfixed_nav = false, wscroll;
var setScroll = function() {
wscroll = $(window).scrollTop();
var fixed_nav = wscroll > 20; // Set pixel amount here
if (fixed_nav != cfixed_nav) {
$('body')[fixed_nav ? 'addClass' : 'removeClass']('fixed');
cfixed_nav = fixed_nav;
}
};
setScroll();
$(document).scroll(setScroll);
});
With CSS you set the fixed position:
.fixed #header {
position: fixed;
top: 0;
left: 0;
right: 0;
width: 100%
}
Also remember, that when the header gets the fixed position, those 20px of the header are missing. So you can add a body padding for example:
.fixed {
padding-top: 20px;
}
Or you add an element with 20 Pixel height and swap display none / block depending on the .fixed class in the body

"Sticky" side bar - setting bottom margin

I have a "sticky" sidebar contact form with jQuery, which turns to fixed-positioned div when page is scrolled down. My problem is that it overlaps the footer when scrolled down all the way. Is there a way where I could set it not to scroll down any further once its bottom margin starts hitting the footer? I'm not sure how I would detect that event, if at all possible, because it's a responsive site and footer's height varies.
CSS:
.sticky {
margin-top: 38px;
max-width: 300px;
padding-top: 20px;
z-index: 0;
}
jQuery:
jQuery(function(){ // document ready
if (!!jQuery('.sticky').offset()) { // make sure ".sticky" element exists
var stickyTop = jQuery('.sticky').offset().top; // returns number
jQuery(window).scroll(function(){ // scroll event
var windowTop = jQuery(window).scrollTop(); // returns number
if (stickyTop < windowTop){
jQuery('.sticky').css({ position: 'fixed', top: 0 });
}
else {
jQuery('.sticky').css('position','static');
}
});
}
Thanks all in advance.

Categories