scrollTop() with slideDown() Not Working Properly - javascript

I'm trying to hide a div if user scrolls down & show it if user scrolls up.
Here's my code,
<div class="baseNav">
# some data
</div>
$(document).ready(function() {
var senseSpeed = 2,
prevScroll = 0;
$(window).scroll(function(e) {
var o = $(this).scrollTop();
var nav = $(".baseNav");
o - senseSpeed > prevScroll ? nav.filter(":not(:animated)").slideUp() : o + senseSpeed < prevScroll ? nav.filter(":not(:animated)").slideDown() : $(window).scrollTop() && nav.filter(":not(:animated)").slideDown(), prevScroll = o
})
});
When user smoothly scrolls down it hides the div, also when user smoothly scrolls up it shows it.
Problem is, in case user scrolls down and then very suddenly scrolls up it doesn't show the div. So, I think it would be a better idea to show the div (in any case) when user (or cursor) is within 100px range from the top.
How can we do that?

by default make the element visible via css
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
if(scrollTop > 100){
$('.elem').hide();
}
else{
$('.elem').show();
}
});

You can show and hide the div using the inbuilt fadeout and fadedin option of javascript and jQuery.
Please try the below one.
$(window).scroll(function() {
if ($(this).scrollTop()>0)
{
$('.fade').fadeOut();
}
else
{
$('.fade').fadeIn();
}
});
body {
height: 2000px;
}
.fade {
height: 300px;
width: 300px;
background-color: #d15757;
color: #fff;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div>
The below div will get faded out on scrolling.
<div class="fade">
Scroll down i will become invisible
</div>
</div>

Related

Dynamically change height of div using onscroll not working

I am trying to use jquery to change the height of a div across a bottom and top nav as on this codepen.
The jquery is this:
$(document).ready(function() {
var lastScrollTop = 0;
var img = 100;
$(window).scroll(function() {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
// downscroll code
console.log('downward')
img = img + 1;
$('.img').height(img);
} else if (st < lastScrollTop) {
// upscroll code
console.log('upward')
img = img - 1;
$('.img').height(img);
}
lastScrollTop = st;
}).scroll();
})
body {
height: 2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Below is the html for the jquery:
<div class='wrapper'>
<nav>
<div class='topnav'>
<div class='img'>
</div>
</div>
<div class='bottomnav'>
</div>
</nav>
<div class='main'>
I am main content
</div>
</div>
The problem is that the console.logs scrolling down doesn't match the console.logs scrolling upwards. So the polygon div spanning both navs doesn't end up where it's supposed to. Please see the image below for console.logs:
I am trying to make the top nav disappear as you scroll the grey nav becomes fixed and the polygon shaped div becomes the size of the grey nav component. The idea is to get a similar effect like the one on fantasy premier leagues website.
Any help would be appreciated. If you need more details please ask and ill provide clarification.
Scrolling upwards and downwards do not always happen in increments of 1, hence the mismatch. If you scroll upwards slowly, its count would exceed downwards scroll. Instead what you need to do is, determine the breakpoints where you want the changes to happen. So for e.g. you want the top navbar to disappear on scroll. The top navbar has height of 50, so when your scrollTop exceeds 50, make grey bar position fixed and at the top. Check this codepen https://codepen.io/anon/pen/RxjoeG
$(document).ready(function () {
var lastScrollTop = 0;
var img = 100;
$(window).scroll(function () {
var st = $(this).scrollTop();
if(st >= 50) {
$('.bottomnav').css({'position':'fixed', 'top':0});
} else {
$('.bottomnav').css({'position':'initial'});
}
}).scroll();
})

Change image shown in fixed div when another div is in viewport

I have a fixed div containing an image that scrolls with the user from the top of the page. As new content divs enter the viewport I want the image to change.
I found a related piece of code that will change the image based on how far a user scrolls in pixels. This works, but only if the viewport is a specific size, else the image changes too early/late:
Example
I'm trying to modify this so that the change is instead based on when another div comes into view so that it works no matter the screen size (content div heights are set with relative units). I think this can be done if the other divs positions are saved to a variable and then used in place of the pixel values in the above code. However I can't seem to get this right, probably because I've not calculated the other div positions correctly.
$("#display1").fadeIn(1000);
$(window).scroll(function() {
var pos = $(window).scrollTop();
var first = $("#first").offset();
var second = $("#second").offset();
if (pos < first) {
hideAll("display1");
$("#display1").fadeIn(1000);
}
if (pos > first && pos < second) {
hideAll("display2");
$("#display2").fadeIn(1000);
}
etc...
});
function hideAll(exceptMe) {
$(".displayImg").each(function(i) {
if ($(this).attr("id") == exceptMe) return;
$(this).fadeOut();
});
}
You should try
getBoundingClientRect()
JS method, since It gets the position of the elements relative to the viewport. Check this answer: https://stackoverflow.com/a/7557433/4312515
Here is a quick proof of concept of changing a background image based on an element getting into view.
There are three divs. When the third div reaches the bottom of the viewport it will change the color of the background. When the third divs scroll out of the view again the background color is reset to its initial color.
Normally you should debounce the scroll event to prevent slowing down the UI. For this example I didn't debounce the event so you get a better sense of when the background is changed.
const
card3 = document.getElementById('card3'),
background = document.getElementById('background');
let
isCardVisible = false;
function checkDivPosition() {
const
cardTopPosition = card3.getBoundingClientRect().top,
viewportHeight = document.documentElement.clientHeight,
isInView = cardTopPosition - viewportHeight < 0;
if (isInView && !isCardVisible) {
background.style.backgroundColor = 'rebeccapurple';
isCardVisible = true;
} else if (!isInView && isCardVisible) {
background.style.backgroundColor = 'orange';
isCardVisible = false;
}
}
function onWindowScroll(event) {
checkDivPosition();
}
window.addEventListener('scroll', onWindowScroll);
body {
margin: 0;
}
.background {
height: 100vh;
opacity: .2;
position: fixed;
transition: background-color .3s ease-out;
width: 100vw;
}
.card {
border: 1px solid;
height: 100vh;
width: 100vw;
}
.card + .card {
margin-top: 5vh;
}
<div id="background" class="background" style="background-color:orange"></div>
<div class="card">
Card 1
</div>
<div class="card">
Card 2
</div>
<div id="card3" class="card">
Card 3.
</div>

Change margin-top position of an fixed positioned element after reaching the bottom of the page?

I need to change top-margin of an fixed div element from margin-top: 200px to margin top 0px after reaching the bottom of the page (or 200px from bottom) using vertical scrollbar.
And toggle return back if scrolling back to the top.
I guess some javascript/jQuery code code do that.
my html/layout code:
<div id="header" style="position: fixed; margin-top: 0px;">
Header content
</div>
<div id="main">
<div id="left" style="position: fixed; margin-top: 200px;">Google Ads here</div>
<div id="right">Content posts here</div>
</div>
<div id="footer">
Footer content
</div>
EDIT: Here are some images to make my question more clear.
normal state when you load the page:
problem when you scroll down, and the google ads column is in conflict with footer:
how it needs to be solved:
Derfder...
Voila, my proposed solution:
http://jsfiddle.net/YL7Jc/2/
The animation's a tad jerky, but I think it does what you want
(It's my take on an earlier s/o post:
Can I keep a DIV always on the screen, but not always in a fixed position? )
Let me know what you think!
Try below code which binds an event to window.scroll to check if the page hits the bottom (bottom in 200px) and moves the #left to top (margin-top: 0)..
DEMO: http://jsfiddle.net/6Q6XY/4/ ( added some demo code to see when it hits the bottom.)
$(function() {
var $left = $('#left');
$(window).bind('scroll', function() {
if (($(document).height()
- (window.pageYOffset + window.innerHeight)) < 200) {
$left.css('marginTop', 0);
} else {
$left.css('marginTop', 200);
}
});
});
Reference: https://stackoverflow.com/a/6148937/297641
You need to implement the window scroll function, this is a jquery implementation so please ensure you include the latest jquery libaries
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
//if it hits bottom
$('#left').css("margin-top", "0px");
}
else {
$('#left').css("margin-top", "200px");
}
});
HTML
<div id="main" style="width: 960px; margin: 0px auto;">
<div id="left" style="position: fixed; top: 200px; left: 0px; background: #000; width: 100%; color: #fff;">Google Ads here</div>
<div id="right"></div>
</div>
JAVASCRIPT
<script type="text/javascript">
$(function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var left = $('#left');
var leftTopPosition = $('#left').css('top');
leftTopPosition = parseInt(leftTopPosition.substring(0, leftTopPosition.length-2));
$(window).scroll(function(){
var pageOffsetY = window.pageYOffset;
if((documentHeight - pageOffsetY - windowHeight) <= 200 && leftTopPosition == 200) {
left.stop().animate({
'top': '0px'
});
leftTopPosition = 0;
}
else if((documentHeight - pageOffsetY - windowHeight) > 200 && leftTopPosition == 0) {
left.stop().animate({
'top': '200px'
});
leftTopPosition = 200;
}
});
});
</script>
Hi Firstly you should have been more clearer in the first place before marking people down, as everyone give similar answers then it shows the question was not clear.
See Js Fiddle for a potential fix, please tweak as you need it with the pixels etc
for this problem you should use z-index in css
Try somethins like this
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
document.getElementById(yourid).setAttribute("style","margin-top:0px");
}
Try this:
$(window).bind('scroll', function(){
if(($(window).height()-$(window).scrollTop())<200)
{
$('#left').css('margin-top',$(window).scrollTop());
}
else
{
$('#left').css('margin-top',200);
}
});

make a div element stick to the top of the screen

I have wrote a script to detect when I reach the div element which is a navigation bar and then I change it's css to position fixed and top 0 so it will be fixed to the top, the problem that it doesn't do that, it acts like scroll to top and it jumps to the beginning of the screen. (it's flickers)
Javascript
var currentScrollTop = 0;
var barMenuOriginalTopPos = $('#navigation').offset().top;
console.log('original:' + barMenuOriginalTopPos);
$(window).scroll(function() {
currentScrollTop = $(window).scrollTop();
console.log(currentScrollTop);
if(currentScrollTop >= barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') == false){
$('#navigation').addClass('fixElementToTop');
}
else if(currentScrollTop < barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') ){
$('#navigation').removeClass('fixElementToTop');
}
});
CSS
.fixElementToTop { position: fixed; top:0; z-index:100;}
Why
Here an non flickering solution via a jQuery plugin:
$(document).ready(function() {
$('#fixedElement').scrollToFixed({ marginTop: 0 });
});
Live example: http://bigspotteddog.github.com/ScrollToFixed/
Plugin's website: https://github.com/bigspotteddog/ScrollToFixed/
a css fixed bar on top of the screen
<div style="position:fixed;top:10px;left:10px">Nav bar</div>
Review:
sorry i didn't understand your initial question, here it goes, to avoid it flicking you should start the object with a fixed position, lets say:
<div style="height:120px">XXX</div>
<div id="navigation" style="position: fixed; top:120; z-index:100;">Navigation</div>
<div class="win" style="border: 1px solid; height: 900px;"></div>
the code:
$(window).scroll(function() {
currentScrollTop = 120-$(window).scrollTop();
console.log(currentScrollTop);
if (currentScrollTop<0) currentScrollTop=0
$("#navigation")[0].style.top=currentScrollTop+"px";
});​
Set this line
var barMenuOriginalTopPos = $('#navigation').offset().top;
as
var barMenuOriginalTopPos = $('#navigation').offset().top + 6;
Refer LIVE DEMO

Once user reaches a particular point on a page, automatically scroll to particular point/achor

So, here it is:
I'll have 4 divs. Example below. Each div a particular height (around 1500px) but have a width of 100%. Each div is a different colour.
I want it so that when the user scrolls the page and reach a particular point, javascript will kick in and automatically scroll the user to the next div.
So, say the user is vertically scrolling and div #2 is appear and div #1 is disappearing. When div #1 has about 200px left, the page will automatically scroll down so that div #2 is flush with the top of the browser window.
A good example: http://thejuly16.com/ Which basically does it but can't work out how.
1
Content here
2
Content here
3
Content here
4
Content here
That page isn't doing anything for me :/
Anyway, if I get what you mean, you should have some anchors on top of every div, hook some code to the scroll event, check scrollTop() value on it, and scroll to the anchors when this value is in a desired range. You can check this fiddle and the relevant jQuery code:
$(window).bind('scroll', function(){
if (($(window).scrollTop() > 1300) && ($(window).scrollTop() < 1350)) {
window.scrollTo(0,1500);
}
});
This might be a strange behavior for the user, since scrolling up is pretty messed up. However, we can fix this by checking if the user is going up or down in the page, like in this fiddle, just checking if the last scroll position was higher or lower than the current scroll position:
var currentScroll = 0;
var previousScroll = 0;
$(window).bind('scroll', function(){
currentScroll = $(window).scrollTop();
if (($(window).scrollTop() > 1300) && ($(window).scrollTop() < 1350) && currentScroll > previousScroll) {
window.scrollTo(0,1500);
}
previousScroll = $(window).scrollTop();
});
Obviously, you'd need to add as many if statements as "jumps" you want in your page.
I have a solution as given in the code below. Somehow its not working on jsFiddle but working on my machine. Please try it in your own editor
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var isWorking = false;
var lastScrollPosition
function adjust(oDiv) {
if(oDiv.scrollTop > lastScrollPosition && !isWorking && oDiv.scrollTop % 400 > 300) {
isWorking = true
scroll(oDiv);
} else
lastScrollPosition = oDiv.scrollTop;
}
function scroll(div) {
if(div.scrollTop % 400 > 10) {
div.scrollTop = div.scrollTop + 10;
lastScrollPosition = div.scrollTop;
setTimeout(function(){scroll(div);}, 10);
} else
isWorking = false;
}
</SCRIPT>
</HEAD>
<BODY>
<div style="height: 440px; border: solid 1px red; overflow-Y: auto" onscroll="adjust(this)">
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 400px; border: solid 1px green"></div>
<div style="height: 100px"></div>
</div>
</BODY>
</HTML>
I think this functionality is available with jQuery. I have tried this but I was doing this on OnClick event in Javascript. In your case, onFocus or any other suitable event like mouseover etc should work.
Hope this helps.

Categories