jQuery Add/Remove Class when Scrolling - javascript

I'm trying to create the following functionality with conditionals...
User scrolls down (120px for example) from the top of the screen, the HTML class 'state-nav-is-hidden' is added to the HTML tag.
When he gets to the BOTTOM after scrolling the class 'state-nav-is-visible' replaces the the HTML class above.
In addition, if the user scrolls and stops before the bottom, then scrolls back up 30px toward the top, 'state-nav-is-visible' replaces the hidden tag.
The following below ONLY accomplishes 1. Any ideas? Thanks!
<script type="text/javascript">
$(function() {
//caches a jQuery object containing the header element
var header = $("html");
$(window).scroll(function(event){
var lastScrollTop = 120;
var st = $(this).scrollTop();
if (st > lastScrollTop){
header.removeClass("state-nav-is-visible").addClass('state-nav-is-hidden');
} else {
header.removeClass('state-nav-is-hidden').addClass("state-nav-is-visible");
}
});
});
</script>

st > lastScrollTop
is the right condition for 1.
st + $(window).height() === document.height
is the consition for 2.
I did not really get point 3, but you have to measure it. Open Chrome and a console as a separate window and type out the current status, like this:
$(window).scroll(function(event){
console.log("Top: " + $(this).scrollTop() + ", Bottom: " + ($(this).scrollTop() + $(window).height()));
});
and then watch the output as you scroll.
EDIT:
Taken into account the comments to the answer I have decided to take a closer look at the fiddle. I understand Mike States, as he wants to solve point 3, but unfortunately it is still unclear for me, but given the fact that he asks so nicely and so consistently for a solution to that problem, I have made a guess. Please, let me know if there is anything wrong with my guess. Everything was written based on your fiddle.
HTML:
<div class="wrapper">
<div class="inner"></div>
</div>
CSS:
div.wrapper {
height:2000px
}
.state-nav-is-visible{
background-color:red;
}
.state-nav-is-hidden{
background-color:green;
}
JS:
$(function() {
//caches a jQuery object containing the header element
var header = $("html");
var reachedBottom = false;
$(window).scroll(function(Event){
var lastScroll = 120;
var st = $(this).scrollTop();
//var bs = $(window).scrollTop() + window.innerHeight == $(document).height();
if (st < lastScroll){
header.removeClass('state-nav-is-hidden').addClass('state-nav-is-visible');
}
else if (st + $(window).height() === document.height) {
header.removeClass('state-nav-is-hidden');
reachedBottom = true;
} else if ((reachedBottom) && (st + $(window).height() <= document.height - 30)) {
reachedBottom = false;
console.log((st + $(window).height() - (document.height - 30)));
}
/*
else if (How do I get current position and if scrolled UP 30 PIXELS do something) {
alert('test');
}
*/
else {
header.addClass("state-nav-is-hidden");
}
});
});

Related

Execute code after scrolling a certain amount of pixels from a certain point (up or down)

I'm currently making an overlay that covers a sticky top bar when the user has scrolled beyond a certain point (down) and disappears when scrolling back up. However, I'd like to be able to scroll for at least 50px before the code is executed (something like a gap before the overlay is triggered).
$(function() {
var prevScroll = $(document).scrollTop(); //initial position
$(window).scroll(function() {
var newScroll = $(document).scrollTop(); //position from top after scrolling
if(newScroll > prevScroll) { // checks if the user has scrolled up or down
var fromNew = $(document).scrollTop(); // holds value to compare with the position + gap amount
if (fromNew > newScroll + 50) { //checks to see if scrolled for 50px
$("#stick-start").fadeIn("fast");
prevScroll = newScroll + 50; //initial position + scrolled amount
};
} else {
var fromNew = $(document).scrollTop();
if (fromNew > newScroll - 50) {
if ($("#stick-start").hasClass("is-stuck")) {
$("#stick-start").fadeOut("fast");
prevScroll = newScroll - 50;
};
};
};
});
});
The condition that checks whether you're scrolling up or down works. But as it is now, the overlay just keeps fading in and out repeatedly. How do I make it so that you have to scroll at least 50px before anything happens ?
I think this should get you where you're going.
var $document = $(document);
$(window).scroll(function() {
if ($document.scrollTop() >= 50) {
$("#stick-start").fadeIn("fast");
} else {
$("#stick-start").fadeOut("fast");
}
});
EDIT: had an error, should be good now.
$(window).scroll(function() {
if ($(this).scrollTop() >= 50) {
$("#stick-start").fadeIn();
} else {
$("#stick-start").fadeOut();
}
});

Make a sticky sidebar?

I want to make my sidebar sticky on my webpage. Just click on a article like this one. On the right side you can see the sidebar. I want that the sidebar comes down if the user slides down and stops at #abspann. But if the user scrolls up again the sidebar should come up as well and stop at the original place.
I already tried this code which can be found here but it isn't working on my website... Can somebody help me please or tell me what I need to do?
Here the code:
<script>
jQuery(function(){
var sidebar = jQuery('#sidebar-wrap'),
nav = jQuery('.sidebar-content'),
startPosition = jQuery('#sidebar-wrap').offset().top,
stopPosition = jQuery('#abspann').offset().top - nav.outerHeight();
jQuery(document).scroll(function () {
//stick nav to top of page
var y = jQuery(this).scrollTop()
if (y > startPosition) {
nav.addClass('sticky');
if (y > stopPosition) {
nav.css('top', stopPosition - y);
} else {
nav.css('top', 0);
}
} else {
nav.removeClass('sticky');
}
});
});
</script>
You'll need to locate ur '$window' position by declaring
var $window = $(window).scrollTop();
Then, you can check if the $window has scrolled passed the point u want, like so:
if (height > 0) {
$('.sidebar-content').addClass('sticky');
} else {
$('.sidebar-content').removeClass('sticky');
}
Keep it simple!
found this thing, its working detection if its up or down. the rest you can just with addclass and remove class.
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
alert("I am an alert box!");
} else {
alert("asfasfasfasf!");
}
lastScrollTop = st;
});
I did put alert boxes to check if it works quickly, so be aware of the spams :D
Tested this in your fiddle and seems to work a treat you just need to make a few amendments to your original code:
var $navWrap = $('#navWrap'),
$nav = $('nav'),
startPosition = $navWrap.offset().top,
stopPosition = $('#stopHere').offset().top - $nav.outerHeight();
$(document).scroll(function () {
//stick nav to top of page
var scrollTop = $(this).scrollTop()
if (scrollTop > startPosition) {
$nav.addClass('sticky');
if (y > stopPosition) {
$nav.css('top', stopPosition - y);
} else {
$nav.css('top', 0);
}
} else {
$nav.removeClass('sticky');
}
});
No js is required. Css only : position:fixed;
https://developer.mozilla.org/en-US/docs/Web/CSS/position#Fixed_positioning
https://caniuse.com/#search=fixed

How to show and hide menu based on start and scroll

I have two menus on a page, I am trying to show the one when the page is loaded and the other when there is a scroll.
This is my page Link
I would like to show the white part when position is at the top
and the blue part when there is a scroll past the top position
This is what am trying presently
<script type="text/javascript" src="//code.jquery.com/jquery-git.js"></script>
<script type='text/javascript'>//<![CDATA[
$(function(){
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('header').removeClass('nav-bar-below op-page-header cf').addClass('banner include-nav');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('banner include-nav').addClass('nav-bar-below op-page-header cf');
}
}
lastScrollTop = st;
}
});//]]>
</script>
can some one please help its not working for me
You can just detect if the scroll is at the top of the page or not whenever scroll event fired. if yes, show white header, and vice versa
$(window).scroll( function() {
var scrollPosition = $(window).scrollTop();
if(scrollPosition === 0) {
//show white header
}
else {
//show blue header
}
}
Of course you have to make sure when page first load, it show the white one first (use css). since the code above won't run Until user do scroll (fire this event)
*EDIT
for this :
"and the blue part when there is a scroll past the top position"
you can try this plugin
http://stickyjs.com/
sample code for fix the menu at top position.
$(document).scroll(function() {
var y = $(document).scrollTop()
var header = $('.include-nav');
var blue-menu = $('.cf');
var screenHeight = header.height();
if (y >= screenHeight) {
blue-menu.css({
position : "fixed",
"top" : "0",
"left" : "0"
});
header.css("position", "relative");
} else {
blue-menu.css("position", "relative");
}
});

Scroll down event 5 times

So what I'm trying to make is changing a fixed background image 4 times ( one scrolldown - one image change) and after the fourth image is up, the div with the images becomes "relative" so I can scroll down to the rest of the content on the website (as well when I scroll up, the images become fixed again and change in a reversed consecutivity).
I decided to use this code, but I'm not sure how to make it work for my 5 scrolls
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
$("#backroundimage").addClass("backgroundimage1"); //down scroll code
} else {
$("#backroundimage").removeClass("backgroundimage1"); //up scroll code
}
lastScrollTop = st;
});
A good example of the functionbility I'm trying to achieve is http://airnauts.com/, after all the scrolling to the top area is done, the website scrolls down to the rest of the content and vice-versa when scrolling up.
After reading the question again I think I understood what you wanna do (I can't open the link you gave).
The thing is that if you want just have a top section that changes its background on scroll you cloud write something like this:
$(document).ready(function(){
var numberofscroll = 0;
var lastScrollTop = 0;
$("#out").scroll(function(){
var st = $(this).scrollTop();
(st > lastScrollTop) ? numberofscroll++ : numberofscroll--;
if (numberofscroll<6){
change_background(numberofscroll);
}
});
lastScrollTop = st;
});
Here a working example I made: https://jsfiddle.net/frqL0y6s/
If you want this 'top section' disapear after the last scroll, you cloud do:
$("#out").scroll(function(){
var st = $(this).scrollTop();
(st > lastScrollTop) ? numberofscroll++ : numberofscroll--;
if (numberofscroll<6){
change_background(numberofscroll);
}
else{
$(this).remove();
}
});
you can try something like
var numberofscroll = 0;
$(window).scroll(function(event){
numberofscroll++;
if($(window).scrollTop() == $(window).height()){ // you reach to window bottom
if(numberofscroll == 1){
// first time scroll
}else if(numberofscroll == 2){
// second time scroll
}else ... so on till you reach to 5
}else{
}
});
Your code can't work because your var lastScrollTop can't egal to st because she is undefined. And more this first variable is useless. Just defined one variable in the loop and make your different test :
$(document).ready(function(){
st = 0;
$(window).scroll(function(event){
st = $(this).scrollTop();
if(st > 200){
test one;
}else if(st > 400){
test two
}else{
default
}
})
})

Get the height of a div jquery

I am trying to make a navigation, that sets the "active" class to links whenever it scrolls a specified ammount of pixels. But there is a div on the page, that get's its size based on user interaction.
This is the code for setting the active class.
$(function() {
//caches a jQuery object containing the header element
var header = $(".active");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >=760) {
header.removeClass('active').addClass("active1");
}
else { header.removeClass('active1').addClass('active');}
});
var header1 = $("#work");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 759 && scroll < 780) {
header1.removeClass('#work').addClass("active");
} else {
header1.removeClass("active").addClass('#work');
}
});
var header2 = $("#about");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 779 && scroll < 1450) {
header2.removeClass('#about').addClass("active");
} else {
header2.removeClass("active").addClass('#about');
}
});
var header3 = $("#contact");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 1449) {
header3.removeClass('#contact').addClass("active");
} else {
header3.removeClass("active").addClass('#contact');
}
});
});
How do I get the height of a div which has it's class set as auto, and then apply it in the code above ?
EDIT: I tried the $('#ID').height(); but it gets the height when the website is loaded, and it doesn't work after any user interacts with the div.
In basically get the height of the DIV
$('#ID').height();
it returns height.
I guess this is what you are looking for
Sample DEMO
if($("#ID").offset().top < $(window).scrollTop() + $(window).outerHeight())
If you create a fiddle possibly can do the same for you
Hope this helps, Thank you

Categories