Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  75] [ 6]  / answers: 1 / hits: 22171  / 10 Years ago, tue, november 4, 2014, 12:00:00

How to make this function add the class after scrolling 100vh?

Currently it adds the class after 850px.



$(document).ready(function($){
var nav = $('#verschwinden');

$(window).scroll(function () {
if ($(this).scrollTop() > 850) {
nav.addClass(doch);
} else {
nav.removeClass(doch);
}
});
});

More From » scroll

 Answers
6

In pure JavaScript use window.innerHeight to get the viewport height, and elScrollable.scrollTop to get the scrollTop of your element.

Use classList.toggle("className", statement) to toggle a class:




const elScrollable = document.querySelector(html)
const elNav = document.querySelector(#nav);

const handleNav = () => {
const viewportHeight = window.innerHeight;
const scrollTop = elScrollable.scrollTop;
elNav.textContent = `Scrolled: ${scrollTop / viewportHeight}`
elNav.classList.toggle(is-active, scrollTop >= viewportHeight);
};

addEventListener(scroll, handleNav)
addEventListener(resize, handleNav)
handleNav();

* {
box-sizing: border-box;
margin: 0;
}

#nav {
position: sticky;
top: 0;
background: silver;
}

#nav.is-active {
background: gold;
}

<nav id=nav>NAV</nav>
<p style=min-height: 300vh>
scroll down until #nav becomes golden...
</p>




Using jQuery use $(window).height() to get the viewport height, and $scrollable.scrollTop() to get how much you scrolled the HTML (or any other) element.

Use .toggleClass("className", statement) to toggle a class:




const $window = $(window);
const $scrollable = $(html);
const $nav = $(#nav);

const handleNav = () => {
const viewportHeight = $window.height();
const scrollTop = $scrollable.scrollTop();
$nav
.text(`Scrolled: ${scrollTop / viewportHeight}`)
.toggleClass(is-active, scrollTop >= viewportHeight);
};

$window.on(scroll, handleNav)
$window.on(resize, handleNav)
handleNav();

* {
box-sizing: border-box;
margin: 0;
}

#nav {
position: sticky;
top: 0;
background: silver;
}

#nav.is-active {
background: gold;
}

<nav id=nav>NAV</nav>
<p style=min-height: 300vh>
scroll down until #nav becomes golden...
</p>

<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js></script>




[#68922] Friday, October 31, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lailab

Total Points: 706
Total Questions: 102
Total Answers: 95

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;