I would like the background of the entire site to change from white to black when a certain element comes into view. So when you scroll by the element the background transitions to black. When you scroll back up I want the background color of the page to change back to white. Thank you!
HTML:
<div id="#block-yui_3_17_2_2_1495044195108_28541" class="colorChange">
<script>
$(window).scroll(function () {
$('#block-yui_3_17_2_2_1495044195108_28541').each(function () {
var topOfWindow = $(window).scrollTop(),
bottomOfWindow = topOfWindow + $(window).height();
var imagePos = $(this).offset().top;
if(imagePos <= bottomOfWindow-100 && imagePos >= topOfWindow-250){
$(this).addClass('colorChange');
}else{
$(this).removeClass('colorChange');
}
});
});
</script>
CSS:
.colorChange{
#siteWrapper {
-webkit-animation-name: colorChange;
-webkit-animation-duration: 1s;
-webkit-animation-timing-function: ease-in;
animation-name: colorChange;
animation-duration: 1s;
animation-timing-function: ease-in;
}}
#-webkit-keyframes colorChange {
0% {
background-color:black;
}
100.0% {
background-color:black;
}
}
#keyframes colorChange {
0% {
background-color:black;
}
100.0% {
background-color:black;
}
}
Using the scroll event you can calculate the offset of the h1 (or whatever element) which gets the current coordinates of the element. the wScroll variable gets the current vertical position of the scroll bar in this case the top of the window. On the condition you check if the scrollbar is greater or equal to the element you which to target and subtract that from the window height (if you wish to change the background once the element is on the screen change the 1.2 to 1) add a transition to the body for the animation. Check the demo scroll down.
Sorry if its not well explained, excuse my writing.
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
if(wScroll >= $('h1').offset().top - ($(window).height() / 1.2 ) ){
$("body").css("background-color", "black");
}else{
$("body").css("background-color", "white");
}
});
body{
transition: background-color 0.3s ease-in-out;
}
p{height: 1000px;}
h1{
height: 400px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hei">
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. </p>
<h1>Change to Black</h1>
</div>
Your $(window).scroll is correct but i think your code lacks the proper setup to do what you want. Here is a working sample i made from your code to change the color of the background when the block div comes into view when scrolling.
https://codepen.io/Nasir_T/pen/jmvwEP
Hope this helps.
If you only want something to happen when the element is in the viewport, you can find the top/bottom positions of the element and compare it to the scrolled distance and bottom of the window.
$(window).on('resize scroll',function() {
var $div = $('div'),
$body = $('body'),
st = $(this).scrollTop(),
wh = $(this).height(),
wb = st + wh,
dh = $div.height(),
dt = $div.offset().top,
db = dh + dt;
if (dt < wb && db > st) {
$body.addClass('color');
} else {
$body.removeClass('color');
}
})
section {
height: 150vh;
}
div {
background: black;
height: 200px;
}
.color {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section></section>
<div></div>
<section></section>
I assume your real issue are the first to lines in your CSS which is not valid. Have a look at the reference. If you want to select all .colorChange inside of #pageWrapper use:
#siteWrapper .colorChange {}
Also remove the "#" in your HTML like so:
<div id="block-yui_3_17_2_2_1495044195108_28541" class="colorChange">
I also would recommend you two throttle your events, so that you do not listen to every scroll event, which could dramatically slow down your system, but every 50 seconds or so. Have a look at ScrollSpy or some jquery throtte plugin.
Related
I spent the weekend trying to get my head around the Intersection Observer Animation for an animation that I'm trying to achieve. From my understanding of the intersection observer my code should work as I intended but the reality is it doesn't 🥲
My goal is that the scroll animation starts when the element reaches a certain point within the viewport. In my codepen, I've marked the point where the animation should start with a border. However, the animation starts as soon as the div enters the viewport.
Also, when the element gets below the border again, the animation should stop.
I would very much appreciate any help to achieve my goal.
Code example: https://codepen.io/aki-sol/pen/RwJPJrW?editors=1111
Also, if you have any feedback on my animation approach I'm very happy to receive criticism/ better way of approaching this.
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
<div class="box">
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
</div>
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
body {
position: relatvie;
heig;
}
body:after {
content: '';
position: fixed;
bottom: 40%;
height: 1px;
width: 100%;
border-bottom: 1px solid blue;
}
.text {
background-color: brown;
color: white;
height: 150vh;
}
.box {
display: flex;
position: relative;
}
.box-content {
width: 200px;
height: 200px;
background-color: greenyellow;
margin-right: 50px;
}
const boxElement = document.querySelector(".box");
//this function calls the aniamtion function and observes the window scroll position
function getWindowScrollPos() {
let windowPosition = window.scrollY;
window.addEventListener("scroll", () => {
windowPosition = window.scrollY;
animateBox(boxElement, windowPosition);
});
}
function animateBox(box, scrollPosition) {
let boxOffsetPosition = scrollPosition;
box.style.left = `${-boxOffsetPosition}px `;
}
function boxObserver(element) {
const observer = new IntersectionObserver(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
getWindowScrollPos();
}
});
},
{ rootMargin: "0% 0% 60% 0%" }
);
observer.observe(element);
}
boxObserver(boxElement);
Thanks a lot!
There are two things to note here, I guess.
First, the Intersection Observer (along with Resize Observer) is not the best thing to test in online sandboxes, because they run code in an iframe, which leads to such a behavior. You should try to run your code in a browser.
There are questions related to this problem. E.g.: In codepen, Intersection observer has different behavior from browser window
Second, you're probably misunderstanding rootMargin. You set it to 0% 0% 60% 0% which means “add 60% of the height of the root to the very root, and use it as a bottom border for intersection”.
What you actually want to is to decrease the bottom border, not to increase. So, just set it to 0% 0% -40% 0% and it will work.
The Intersection Observer tutorial that helped me a bit to understand the rootMargin weirdness. Maybe it will be useful for you too.
Demo
Here's your snippet that I changed a bit to make it work inside an iframe. I've added a container node and use it instead of window.
const boxElement = document.querySelector('.box');
const container = document.getElementById('container');
function setupListener() {
let scrollPosition = container.scrollTop;
animateBox(boxElement, scrollPosition);
container.addEventListener('scroll', () => {
scrollPosition = container.scrollTop;
animateBox(boxElement, scrollPosition);
});
}
function animateBox(box, scrollPosition) {
let boxOffsetPosition = scrollPosition;
box.style.left = `${-boxOffsetPosition}px`;
}
function boxObserver(element) {
const observer = new IntersectionObserver(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setupListener();
}
});
},
{
root: document.getElementById('container'),
rootMargin: `0px 0px -40% 0px`
}
);
observer.observe(element);
}
boxObserver(boxElement);
body {
margin: 0;
overflow: hidden;
}
body:after {
content: "";
position: fixed;
bottom: 40%;
height: 1px;
width: 100%;
border-bottom: 1px solid blue;
}
.container {
overflow: scroll;
max-height: 100vh;
}
.text {
background-color: brown;
color: white;
height: 150vh;
}
.box {
display: flex;
position: relative;
}
.box-content {
width: 200px;
height: 200px;
background-color: greenyellow;
margin-right: 50px;
}
<div class="container" id="container">
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
<div class="box">
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
</div>
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
</div>
What may be improved
Also, if you have any feedback on my animation approach I'm very happy to receive criticism/ better way of approaching this.
Well, you surely should think about the scroll listener you will have after the intersection started. If you don't remove it, it will hang. Or even worse, they will be increasing during each intersection. Not a good thing.
Also it's better to animate transform, not left. It's good for optimization. Otherwise you'll get junky animation which will freeze the whole site. Check this set of articles by Google: web.dev/animations/.
I'm trying to make a header that is sticky when scrolling upwards and not showing when scrolling downwards using javascript, to do that I added a class .header-up and gave transform: translateY(-100%); through CSS. It's working perfectly fine, BUT when I open the full-page menu in header and trying to close [no issues when header at the top, but we can see the problem after scrolling a bit from top] it the class 'header-up' is still there. So the header going upwards behind the viewport area. I tried to remove the .header-up class using this code s.removeClass("header-up") to make the header stick at the same place. Here goes the jsFiddle
here is the javascript I used for scroll and toggle the full page menu.
$( document ).ready(function() {
var scroll_pos = 0;
var scroll_time;
$(window).scroll(function() {
clearTimeout(scroll_time);
var current_scroll = $(window).scrollTop();
if (current_scroll >= $("#header").outerHeight()) {
if (current_scroll <= scroll_pos) {
$("#header").removeClass("header-up");
} else {
$("#header").addClass("header-up");
}
}
scroll_time = setTimeout(function() {
scroll_pos = $(window).scrollTop();
}, 100);
});
});
$("#navbar-toggle").on("click", function(t) {
var e = $(this).data("scroll-y"),
i = $(window).scrollTop(),
n = $("#navbar-toggle"),
o = $("#overlay-nav"),
s = $("#header"),
r = $("body");
o.hasClass("toggle")
? (r.css("top", "0px").removeClass("noscroll"),
window.scrollTo(0, e),
o.removeClass("toggle"),
n.removeClass("open"),
s.removeClass("overlay-nav-toggled"),
s.removeClass("pos-fixed"),
s.removeClass("header-up"),
setTimeout(function() {
s.removeClass("suppress-scroll");
}, 700))
: ($(this).data("scroll-y", i),
o.addClass("toggle"),
n.addClass("open"),
s.addClass("overlay-nav-toggled suppress-scroll"),
r.css("top", -i + "px").addClass("noscroll"));
});
update this
if (current_scroll <= scroll_pos) {
with the following
if (current_scroll <= scroll_pos || $('#header').hasClass('suppress-scroll')) {
I don't fully understand your question, but is this what you're looking for?
var lastScrollTop = 0;
var headerElement = $('header');
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// scroll down
headerElement.addClass('header-hidden');
} else {
// scroll up
headerElement.removeClass('header-hidden');
}
lastScrollTop = st;
});
body {
background: #f5f5f5;
position: relative;
}
header {
background: white;
height: 50px;
position: fixed;
top: 0;
left: 0;
right: 0;
padding: 15px;
transition: 500ms margin-top ease;
}
header.header-hidden {
margin-top: -100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<p>header</p>
</header>
<p>accusantium, omnis aut quod, optio eius qui voluptates quae? Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint natus rerum cum harum possimus, repellendus alias! Necessitatibus doloremque magnam ex sunt accusantium, omnis aut quod, optio eius qui voluptates quae?Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint natus rerum cum harum possimus, repellendus alias! Necessitatibus doloremque magnam ex sunt accusantium, omnis aut quod, optio eius qui voluptates quae? Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint natus rerum cum harum possimus, repellendus alias! Necessitatibus doloremque magnam ex sunt accusantium, omnis aut quod, optio eius qui voluptates quae? Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint natus rerum cum harum possimus, repellendus alias! Necessitatibus doloremque magnam ex sunt accusantium, omnis aut quod, optio eius qui voluptates quae? Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint natus rerum cum harum possimus, repellendus alias! Necessitatibus doloremque magnam ex sunt accusantium, omnis aut quod, optio eius qui voluptates quae? Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint natus rerum cum harum possimus, repellendus alias! Necessitatibus doloremque magnam ex sunt accusantium, omnis aut quod, optio eius qui voluptates quae?Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint natus rerum cum harum possimus, repellendus alias! Necessitatibus doloremque magnam ex sunt accusantium, omnis aut quod, optio eius qui voluptates quae?</p>
Edit
Based on the feedback of the owner of this question:
The reason that the header is gone when you click on the button is because your #overlay-nav has position: fixed combined with a top: 0
the header is still there, but your menu elements are on top off it.
either change z-index values or change the top: 0 values
the code underneath will fix your issue, but don't forget to check responsive because you're setting a static value right now
#overlay-nav {
top: 100px;
}
I want to positioned a div box fixed every time I scroll down the page as touch that box and keep scrolling down so that it never disappears after a user sees it.
$(window).scroll(function() {
if($('section#top_casino_offer').scrollTop() +
$('section#top_casino_offer').innerHeight() >= $('section#top_casino_offer')[0].scrollHeight) {
console.log('show');
} else {
console.log('hide');
}
});
I made a quick snippet for it here
I tried the code above but it does not work.
you could specify a scrolling value like this, Check the following snippet :
$(window).scroll(function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 90;
// set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test) {
$("#top_casino_offer").css("position","fixed");
}
else
{
$("#top_casino_offer").css("position","relative");
}
});
.outer{
height: 1100px;
background: green;
width: 100%;
}
#yellow{background: yellow;
}
#top_casino_offer {
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<p>Paragraph</p>
<section id="yellow">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut doloremque repellendus eligendi, dolorem vel sapiente harum repellat voluptatum hic, officiis perspiciatis dolor labore maiores cumque eos necessitatibus non ex, fuga.</p>
</section>
<section id="top_casino_offer">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut doloremque repellendus eligendi, dolorem vel sapiente harum repellat voluptatum hic, officiis perspiciatis dolor labore maiores cumque eos necessitatibus non ex, fuga.</p>
</section>
</div>
hope this helps :)
On the following website i have a navigation bar.
http://bit.do/bVXAs
I use this css code for the navigation:
z-index: 999;
position: relative;
background: #302f2f; /* Old browsers */
background: -moz-linear-gradient(top, #302f2f 0%, #000000 100%);
background: -webkit-linear-gradient(top, #302f2f 0%,#000000 100%);
background: linear-gradient(to bottom, #302f2f 0%,#000000 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#302f2f',
endColorstr='#000000',GradientType=0 ); /* IE6-9 */
box-shadow: 0px 7px 31px -5px #000;
border-bottom: 15px solid #ff9500;s
An i use a Javascript Code for the position fixed:
$(window).scroll(function () {
if ($(window).scrollTop() > 1) {
$('#navigationsleiste').css('top', $(window).scrollTop());
}
}
Now when i scroll the Navigation Bar have a space to the top of the browser window. But i dont want that space/gap. Know anyone why i have that gap/space?
The answer to 'Why the gap' has been answered in the comments I believe.
More generally, on how to fix the issue:
CSS has a position property that's very suited for your sticky menu: position: fixed. When the menu is scrolled outside of view, you change its position to fixed. Once it's back at its original location, you remove your fixed positioning.
You want to do as little as possible in a method that is executed on scroll, since it is triggered very often. Once there's too much code execution on a scroll, you loose your smooth 60fps framerate.
So what you could do is:
Make sure you always know how far the top of your sticky menu is away from the top of your window
On scroll, check if this point has been reached
Add or remove a class to your menu accordingly
Here's an example:
$(document).ready(function() {
var $doc = $(document);
var $menu = $("nav");
var menuTop = 0;
var setMenuTop = function() {
menuTop = $menu.offset().top;
}
$(window).resize(setMenuTop);
$doc.scroll(function() {
$menu.toggleClass("is-fixed", ($doc.scrollTop() > menuTop));
});
setMenuTop();
});
body {
width: 400px;
margin: 0 auto;
}
header {
height: 160px;
background: orange;
}
nav {
heigth: 40px;
background: yellow;
will-change: transform;
}
nav.is-fixed {
position: fixed;
width: 400px;
top: 0;
}
.is-fixed + article {
margin-top: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>header</header>
<nav>menu</nav>
<article>
<h1>content</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam nulla enim placeat? Iure modi quasi facere provident, quidem ducimus impedit nulla harum sunt corrupti. Rem velit architecto omnis molestias, repellat.</p>
</article>
Instead $(window) set it better on $(document):
$('#navigationsleiste').css('top', $(document).scrollTop());
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to create a floating menu that will stay on top when scrolling. I found some examples and was able to replicate them and it now works.
However, the problem is that as you can see in the example, when I scroll, the text below the menu when scrolling "jumps up", it is difficult to explain what I mean, but if you look at it, you will immediately see what the problem is. Could anyone help me with fixing this?
Add .sectionHeading a dynamic margin:top equal to the height of the menu, with the same event that triggers the fixed class.
You need to do this on a trial and error basis. And you need to change a static parent. Check this example and follow it.
Snippet
$(function () {
$(window).scroll(function () {
if ($(window).scrollTop() > 125)
$("body").addClass("fixed");
else
$("body").removeClass("fixed");
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
h1, h2 {font-weight: normal;}
h1 {font-size: 1.5em;}
h2 {font-size: 1.25em;}
h1, h2, p {margin: 0 0 15px;}
.fixed {padding-top: 42px;}
.fixed .static {position: fixed; top: 0; width: 100%; background: #fff; padding-bottom: 15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1>Static Header Example</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At, cumque inventore laudantium quod, vel pariatur dolore obcaecati veniam aspernatur aliquam ad dolorum possimus illo facilis et totam nam unde, sint?</p>
<h2 class="static">This is gonna be Static!</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis tempore praesentium eos odio nobis dignissimos labore expedita corrupti sapiente perferendis consequuntur, in, eveniet error! Officiis iste architecto eos? Deserunt, delectus!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit, blanditiis dolore ipsum odit sint delectus assumenda excepturi dolor rem aperiam magni eligendi quidem suscipit nam ullam porro tenetur tempora ut!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis tempore praesentium eos odio nobis dignissimos labore expedita corrupti sapiente perferendis consequuntur, in, eveniet error! Officiis iste architecto eos? Deserunt, delectus!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit, blanditiis dolore ipsum odit sint delectus assumenda excepturi dolor rem aperiam magni eligendi quidem suscipit nam ullam porro tenetur tempora ut!</p>
When you're changing the class of the your menu from default to fixed the height of your document will reduce by the height of your menu because you have changed the display of your menu.
The solution is that when you change the class of the menu from default to fixed you can add some padding to your document's body (the height of the menu element is fine) and remove the padding when changing the class of the menu from fixed to default.
$(function(){
var menu = $('#menu'),
pos = menu.offset();
$(window).scroll(function(){
if($(this).scrollTop() > pos.top && menu.hasClass('default')){
menu.hide(1, function(){
$(this).removeClass('default').addClass('fixed').show(1);
$('body').css('padding-top', '111px');
});
} else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){
menu.hide(1, function(){
$(this).removeClass('fixed').addClass('default').show(1);
$('body').css('padding-top', '0');
});
}
});
});
You can add another div like your menu but with class="fixed" and display: none, when the scroll reaches the top of the page, you can show that div and change the visibility of the #menu from visible to hidden.