Get the scrolled position of an element whan scrolling up - javascript

I'm doing simple check how much the page scrolled to put an element on the page/hide it.For scrolling down everything works just fine,but whan going back it does nothing.Also have in mind that the first container on the page is 100vh,so i took it as reference whan to show/hide.my code is as follows:
HTML:
<div id="toTop">⇑</div>
CSS:
#toTop {
position: fixed;
right: 25px;
bottom: 25px;
}
#toTop a {
display: block;
width: 25px;
height: 50px;
font-size: 50px;
color: #31ddb7;
opacity: 0;
}
jQuery:
var windowHeight = $(".testimonials").offset().top,
lessHeight = windowHeight + 40;
$(window).on('scroll',function(){
var arrowScroll = $(window).scrollTop();
if(arrowScroll >= windowHeight) {
$("#toTop a").css("opacity", "1");
}else if (arrowScroll <= lessHeight) {
$("#toTop a").css("opacity", "0");
console.log(windowHeight);
}else {
return false;
}
});
Once again,distance to .testimonials from top is 100vh.
code goes to first if statement but not to the else if.I have also tryed with just if/else,but it whant work as well.

Your code if working properly and in fact the statement goes in the else if. I'm not sure what the exact problem is you're asking help for.

Related

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

jQuery sticky header flashes at specific height

I am using following code to make a menu sticky when the window is scrolled down. It works fine if the window height is enough to scroll down the full header area, but it it creates problem is the height is just close enough to scroll, in that case it starts flashing and does not let scroll.
Here is the demo of the problem, refresh couple of times and try to scroll down. I have set the body height to 622px to reproduce the problem:
http://jsbin.com/ipEROYO/1
Here's the code I'm trying:
$(document).ready(function() {
var stickyNavTop = $('.nav').offset().top;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
});
CSS:
.sticky {
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
}
It's because when you are setting the navigation div to position:fixed you are shortening the length of the document (by the height of that div), which then causes the scroll bar to go away, which causes the scrollTop() value to be 0 which causes the .nav div to be position:static and it is an endless cycle if you keep scrolling down.
Here's my quick solution:
$(document).ready(function() {
var height = $('.nav').outerHeight();
$(window).scroll(function() {
if($(this).scrollTop() > height)
{
$('.nav').css('position','fixed');
$('body').css('padding-bottom',height+'px');
}
else if($(this).scrollTop() <= height)
{
$('.nav').css('position','static');
$('body').css('padding-bottom','0');
}
});
$(window).scroll();
});
Just modified the JSbin. Check it out. You were really close, just doing more than you needed to like setting the sticky class on load of the page rather than when the function first runs. Let me know if this helps.
try that
$(window).scroll(function () {
var scroll_top = $(this).scrollTop();
if (scroll_top > 66) {//height of header
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
});
Strongly recommend a CSS only solution for this layout. No one seems to know what to call this method, so I've been referring to it as the absolute stretch technique, but in my experience it works beautifully across mobile devices and PC's including all major browsers except IE6 and below. There is some discussion of it here.
body, .header, .nav, .mainContent{
position: absolute;
top: 0;
left: 0;
right: 0;
}
body, .mainContent {
bottom: 0;
}
.header{
height: 120px;
}
.nav{
height: 70px;
top: 120px;
}
.mainContent{
top: 190px;
overflow: auto;
}
You'll find you can get very robust, concise, well organized layouts in this manner, and fixed headers, footers and sidebars follow very easily.

Float a div at the bottom right corner, but not inside footer

I'm trying to implement a "go to top" button that floats at the bottom right corner of a page. I can do this with the following code, but I don't want this button to enter the footer of my page. How can I stop it from entering the footer and stay at the top of it when user scrolls the page down to the bottom of the page?
CSS
#to-top {
position: fixed;
bottom: 10px;
right: 10px;
width: 100px;
padding: 5px;
border: 1px solid #ccc;
background: #f7f7f7;
color: #333;
text-align: center;
cursor: pointer;
display: none;
}
JavaScript
$(window).scroll(function() {
if($(this).scrollTop() != 0) {
$('#to-top').fadeIn();
} else {
$('#to-top').fadeOut();
}
});
$('#to-top').click(function() {
$('body,html').animate({scrollTop:0},"fast");
});
HTML
<div id="to-top">Back to Top</div>
EDIT
Here is a drawing of how it should look like. The black vertical rectangle is a scroll bar. The "back to top" button should never enter the footer region.
Here is a jsfiddle.
The solution turned out to be more complicated than I thought. Here is my solution.
It uses this function to check if footer is visible on the screen. If it is, it positions the button with position: absolute within a div. Otherwise, it uses position: fixed.
function isVisible(elment) {
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elment).offset().top;
return y <= (vpH + st);
}
$(window).scroll(function() {
if($(this).scrollTop() == 0) {
$('#to-top').fadeOut();
} else if (isVisible($('footer'))) {
$('#to-top').css('position','absolute');
} else {
$('#to-top').css('position','fixed');
$('#to-top').fadeIn();
}
});
jsfiddle
Increase the value of bottom: 10px; than the height of footer.
I saw your screenshot now,just add some padding-bottom to it.
Solution
$(document).ready(function(){
$(window).scroll(function(){
btnBottom = $(".btt").offset().top + $(".btt").outerHeight();
ftrTop = $(".footer").offset().top;
if (btnBottom > ftrTop)
$(".btt").css("bottom", btnBottom - ftrTop + $(".btt").outerHeight());
});
});
Fiddle: http://jsfiddle.net/praveenscience/BhvMg/
You forgot to give the z-index, that prevents it from being on top!
z-index: 999;
Or if it is overlapping with the footer of your page, you can increase the co-ordinates.
bottom: 50px;
Your question is still not clear, "stop it from entering the footer". Does it overlap?

How to trigger the layout to change?

I've a sticked element which gets the top-alignment from current scroll-offset. Problem is, that the layout is not "retriggerd" if the space from it is free. So there stays a ghost-gap where the sticked element was...
http://fiddle.jshell.net/pPc4V/
The markup is pretty simple:
...
as well as the js:
var $win = $(this);
var sticked = document.querySelector('a.sticked');
$win.on('scroll', function () {
var scrollTop = $win.scrollTop();
sticked.style.top = scrollTop + 'px';
// $win.resize();
});
...and the css looks good so far:
a {
display: inline-block;
width: 90px;
height: 90px;
background: deepskyblue;
}
.sticked {
position: relative;
top: 0;
left: 0;
background: tomato;
}
I tried to trigger the resize-event on scroll (as you see above uncommented), but no success! Any ideas, how to retrigger the layout so that the free-gap is filled with the next floated element?
Update
To clarify what I mean I made a simple image-timelime:
Step 1
Step 2
Step 3
The issue is that you are setting position fixed on an element which is displayed inline. That will cause that space to occur. I have redid your jsFiddle with proper alignment.
To fix it, I added the class "stuck" only when the document's scrollTop position is greater than the scrollTop position of your target element.
jsFiddle: http://fiddle.jshell.net/pPc4V/44/
HMTL:
<div id="grid">
etc...
</div>
CSS:
#grid {
height:1000px;
overflow:hidden;
float:left
}
#grid > a {
display: inline-block;
width: 90px;
height: 90px;
background: deepskyblue;
}
.stuck {
position: fixed;
background: navy !important;
}
JS:
$(window).on('scroll', function () {
var $doc = $(document),
parentElement = $('#grid'),
childToGetStuck = parentElement.find('a:nth-child(5)');
if ($doc.scrollTop() > childToGetStuck.scrollTop()) {
childToGetStuck.addClass('stuck');
//console.log($('.stuck').scrollTop())
} else {
childToGetStuck.removeClass('stuck');
}
});

Categories