Sticky navigation bar doesn't work - javascript

I am trying to create a navigation bar that sticks to the top of the screen after some scrolling. I followed two different tutorials but I can't seem to make either of them work properly.
The first tutorial does not stick to the top of the screen at all. The second tutorial does stick to the top of the screen, but if you scroll down far enough, you can't see the navigation until after it sticks to the top.
This is what I have right now (following the first tutorial):
var n = $("#nav-bar");
ns = "nav-bar-scrolled";
hdr = $('#nav-bar').offset().top;
$(window).scroll(function(){
if($(this).scrollTop() > hdr){
n.addClass(ns);
}else{
n.removeClass(ns);
}
});
This is the JS code following the second tutorial:
$(function(){
// Check the initial Poistion of the Sticky Header
var stickyHeaderTop = $('header').height();
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#nav-bar').css({position: 'fixed', top: '0px'});
$('#stickyalias').css('display', 'block'); //this doesn't do anything
} else {
$('#nav-bar').css({position: 'static', top: '0px'});
$('#stickyalias').css('display', 'none'); //this doesn't do anything
}
});
});
Full code here: https://jsfiddle.net/linahsie/rhp65j2b/2/
Thank you!

In your JS, n should be #nav-bar, ns (since you're toggling a class) should be nav-bar-scrolled, and hdr should be the bottom position of the header, since that's the point where you want the nav to affix itself to the top of the window. Then in your CSS, you want to use #nav-bar.nav-bar-scrolled as the selector for the fixed menu to match the changes you're making in your JS.
var n = $("#nav-bar");
ns = "nav-bar-scrolled";
hdr = $('header').offset().top + $('header').outerHeight();
$(window).scroll(function(){
if($(this).scrollTop() > hdr){
n.addClass(ns);
}else{
n.removeClass(ns);
}
});
/*
$(function(){
// Check the initial Poistion of the Sticky Header
var stickyHeaderTop = $('header').height();
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('nav').css({position: 'fixed', top: '0px'});
$('#stickyalias').css('display', 'block');
} else {
$('nav').css({position: 'static', top: '0px'});
$('#stickyalias').css('display', 'none');
}
});
});
*/
/*
$(function () {
// Check the initial Poistion of the Sticky Header
var stickyHeaderTop = $('nav').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > stickyHeaderTop) {
$('nav').css({
position: 'fixed',
top: '0px'
});
$('#about').css('margin-top', $('nav').outerHeight(true) + parseInt($('header').css('marginBottom')));
} else {
$('nav').css({
position: 'static',
top: '0px'
});
$('#about').css('margin-top', '0px');
}
});
});
*/
*{
margin: 0;
padding: 0;
}
.container{
margin-right: auto;
margin-left: auto;
width: 1000px;
}
header{
height: 100vh;
background: #f07057;
}
#after-header{
padding-top: 100vh;
}
#nav-bar,
#about,
#a2{
position: relative;
}
#header-content{
position: absolute;
top: 50%;
left: 50%;
}
#nav-bar{
height: 75px;
font-family: 'Montserrat';
background-color: #FFE77C;
z-index: 150;
width: 100%;
}
header{
position: fixed;
width: 100%;
}
#nav-bar.nav-bar-scrolled{
top: 0;
z-index: 100;
position: fixed;
width: 100%;
}
#nav-bar h1{
padding-top: 10px;
font-size: 270%;
text-align: center;
float: left;
}
#nav-list{
float: right;
}
.dir{
float: left;
padding-top: 25px;
text-decoration:none;
padding-left: 15px;
}
#about{
height: 100vh;
background-color: antiquewhite;
}
#a2{
height: 100vh;
background-color: beige;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<header>
<div id="header-content">
<h1>Text Here</h1>
</div> <!--header-content-->
</header>
<div id="after-header">
<nav id="nav-bar">
<div class="container">
<h1>Nav Bar</h1>
</div> <!--container-->
</nav> <!--nav-->
<div id="about">
<div class="container">
<h1>Hello, world!</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>
</div> <!--end of about-->
<div id="a2">
<div class="container">
<h1>Hello, world!</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>
</div>
</div> <!--end of after-header-->
</body>

Had a look at the jquery, you define var n = $("#nav"); but you don't have a nav with id="nav", change to n = $("#nav-bar");

Related

Display slider like drawer on clicking box

I have two boxes, Now When the user clicks on LeftToRight then I have to slide content from left to right with LeftToRight box. if the user clicks on RightToLeft the I have to slide the div from right to left.
I tried below code but it's not displaying properly when clicking on the button. I want like a drawer.
Can anyone help me out with this issue?
$(document).ready(function() {
$("#clickLeft").click(function() {
$(".leftoRightbox").animate({
width: "toggle"
});
if (!$('.innerWrapper').hasClass("hidesecondbox")) {
$('.innerWrapper').addClass('hidesecondbox');
} else {
$('.innerWrapper').removeClass('hidesecondbox');
}
});
$("#clickRight").click(function() {
$(".righttoLeftbox").animate({
width: "toggle"
});
if (!$('.innerWrapper').hasClass("hidefirstbox")) {
$('.innerWrapper').addClass('hidefirstbox');
} else {
$('.innerWrapper').removeClass('hidefirstbox');
}
});
});
.innerWrapper {
text-align: center;
display: flex;
justify-content: center;
}
.box {
width: 200px;
height: 200px;
background-color: #f8f8f8;
border: 1px solid #ccc;
}
.displayflex {
display: flex;
overflow: hidden;
}
.leftoRightbox,
.righttoLeftbox,
.goback,
.hidefirstbox .one,
.hidesecondbox .two {
display: none;
}
.leftoRightbox,
.righttoLeftbox {
height: 400px;
}
<div class="mainWrapper">
<div class="innerWrapper">
<div class="displayflex one">
<div class="leftoRightbox">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="leftoRight box" id="clickLeft">
<h2>This is slide left to right</h2>
<p class="goback">Go Back</p>
</div>
</div>
<div class="displayflex two">
<div class="righttoLeft box" id="clickRight">
<h2>This is slide right to left</h2>
<p class="goback">Go Back</p>
</div>
<div class="righttoLeftbox">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Add flex-shrink:0; to box element and define a fixed width for the p element to avoid the bad effect when doing the animation:
$(document).ready(function() {
$("#clickLeft").click(function() {
$(".leftoRightbox").animate({
width: "toggle"
});
if (!$('.innerWrapper').hasClass("hidesecondbox")) {
$('.innerWrapper').addClass('hidesecondbox');
} else {
$('.innerWrapper').removeClass('hidesecondbox');
}
});
$("#clickRight").click(function() {
$(".righttoLeftbox").animate({
width: "toggle"
});
if (!$('.innerWrapper').hasClass("hidefirstbox")) {
$('.innerWrapper').addClass('hidefirstbox');
} else {
$('.innerWrapper').removeClass('hidefirstbox');
}
});
});
.innerWrapper {
text-align: center;
display: flex;
justify-content: center;
}
.box {
width: 200px;
height: 200px;
background-color: #f8f8f8;
border: 1px solid #ccc;
flex-shrink:0;
}
.displayflex {
display: flex;
overflow: hidden;
}
.leftoRightbox,
.righttoLeftbox,
.goback,
.hidefirstbox .one,
.hidesecondbox .two {
display: none;
}
.leftoRightbox p,
.righttoLeftbox p{
width:calc(100vw - 280px);
}
<div class="mainWrapper">
<div class="innerWrapper">
<div class="displayflex one">
<div class="leftoRightbox">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="leftoRight box" id="clickLeft">
<h2>This is slide left to right</h2>
<p class="goback">Go Back</p>
</div>
</div>
<div class="displayflex two">
<div class="righttoLeft box" id="clickRight">
<h2>This is slide right to left</h2>
<p class="goback">Go Back</p>
</div>
<div class="righttoLeftbox">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Add class active to the li when respective section is on screen

I have a single page. I have min four sections on my page. I have to add the active class to the li tag on the menu when scrolling at the bottom with the respective section. For example, If about us section is on the screen then add class active to the li tag. If the gallery section is on the screen then add active class and remove the active class from the previous li.
I have to change the color and adding the bottom border to the active menu list. I don't want to use any plugin.
This is an example. It's adding the class active and changing the color of nav list
https://blackrockdigital.github.io/startbootstrap-scrolling-nav/
Is it possible to use jQuery?
$(function() {
$('.smothscrollclass a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - 100
}, 1000);
return false;
}
}
});
});
body {
margin: 0;
padding: 0;
}
.headerMenu {
position: fixed;
top: 0;
width: 100%;
background-color: #d9a6a6;
}
.anchorLinks ul {
list-style: none;
}
.anchorLinks ul li {
display: inline-block;
margin: 15px;
}
.anchorLinks ul li a {
color: #fff;
text-decoration: none;
font-size: 18px;
}
.anchorLinks ul li.active a {
color: #ffef00;
border-bottom: 1px solid #000;
}
.WrapperInner {
margin-top: 80px;
margin-bottom: 80px;
}
section {
height: 400px;
padding: 40px;
}
section p {
color: #fff;
}
.aboutus {
background-color: #ec7063;
}
.service {
background-color: #a569bd;
}
.gallery {
background-color: #5dade2;
}
.contactus {
background-color: #2ecc71;
}
<div class="Wrapper">
<div class="mainInner bg_white">
<div class="linkWrappers">
<header class="headerMenu">
<div class="anchorLinks smothscrollclass">
<ul>
<li>Home</li>
<li>About</li>
<li>Service</li>
<li>Gallery</li>
<li>Contact</li>
</ul>
</div>
</header>
</div>
<div class="WrapperInner ">
<section class="aboutus" id="aboutus">
<h2>About us</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="service" id="service">
<h2>Service</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="gallery" id="gallery">
<h2>Gallery</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="contactus" id="contactus">
<h2>Contact us</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
hi follow up the below snippet what I do here is made an one function called activateLink and I gave ID to links and clicking the link I add an active class to that particular li with the help of jquery
$(function() {
$('.smothscrollclass a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - 100
}, 1000);
return false;
}
}
});
});
function activateLink (link,section) {
if(section){
$('html, body').animate({
'scrollTop' : $("#"+section).position().top
},function(){
$( ".active" ).removeClass( "active" )
$("#"+link).addClass("active");
});
}else{
$( ".active" ).removeClass( "active" )
$("#"+link).addClass("active")
}
}
function checkSectionExistance (sectionId,linkId) {
var element = document.querySelector('#'+sectionId);
var position = element.getBoundingClientRect();
// checking for partial visibility
if(position.top < window.innerHeight && position.bottom >= 0) {
$( ".active" ).removeClass( "active" )
$("#"+linkId).addClass("active")
}
}
window.addEventListener('scroll', function() {
checkSectionExistance('aboutus','about-link')
checkSectionExistance('service','service-link')
checkSectionExistance('gallery','gallery-link')
checkSectionExistance('contactus','contact-link')
});
body {
margin: 0;
padding: 0;
}
.headerMenu {
position: fixed;
top: 0;
width: 100%;
background-color: #d9a6a6;
}
.anchorLinks ul {
list-style: none;
}
.anchorLinks ul li {
display: inline-block;
margin: 15px;
}
.anchorLinks ul li a {
color: #fff;
text-decoration: none;
font-size: 18px;
}
.anchorLinks ul li.active a {
color: #ffef00;
border-bottom: 1px solid #000;
}
.WrapperInner {
margin-top: 80px;
margin-bottom: 80px;
}
section {
height: 400px;
padding: 40px;
}
section p {
color: #fff;
}
.aboutus {
background-color: #ec7063;
}
.service {
background-color: #a569bd;
}
.gallery {
background-color: #5dade2;
}
.contactus {
background-color: #2ecc71;
}
a{
cursor:pointer
}
.active {
border-bottom:1px solid white
}
<div class="Wrapper">
<div class="mainInner bg_white">
<div class="linkWrappers">
<header class="headerMenu">
<div class="anchorLinks smothscrollclass">
<ul>
<li><a id='home-link' onclick="activateLink('home-link')">Home</a></li>
<li><a id='about-link' onclick="activateLink('about-link','aboutus')" >About</a></li>
<li><a id='service-link' onclick="activateLink('service-link','service')" >Service</a></li>
<li><a id='gallery-link' onclick="activateLink('gallery-link','gallery')" >Gallery</a></li>
<li><a id='contact-link' onclick="activateLink('contact-link','contactus')" >Contact</a></li>
</ul>
</div>
</header>
</div>
<div class="WrapperInner ">
<section class="aboutus" id="aboutus">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="service" id="service">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="gallery" id="gallery">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="contactus" id="contactus">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
let me know if it's helpful
with pure js you need to use document.body.scrollTop; to define how much was scrolled then remove style active from all li-s and add to the current or just manually for each remove the previous for(let i = 0;i<liClass.length;i++){liClass[i].classList.remove("active")} then add to the current targetting it by ID or unique class, works fine for me for jQuery is the same just $("body").scrollTop()
I upgraded a bit now everything is crystal clear ;)
For scrolls I used pure html just add ID to the element where you want to scroll and add <a href="#theIdOfElement">
the classes I did with jQuery as you asked
2nd EDIT:
let x=0;
$(document).ready(()=>{
$("a").click((e)=>{
//Removes class active from all a-s and all divs
$("a").removeClass("active");
$("div").removeClass("active");
//Adds only to clicked one
$(e.target).addClass("active");
//Adds class active to divs that contain the text on which you clicked
$("div:contains("+ $(e.target).text() +")").addClass("active");
});
$(document).scroll(()=>{
$("p").text( $(document).scrollTop());
if($(document).scrollTop() >= 970){
//If you want to get style permenent remove line below
$("div").removeClass("active");
$("#contacts").addClass("active");
}
else if($(document).scrollTop() >= 508){
//If you want to get style permenent remove line below
$("div").removeClass("active");
$("#about").addClass("active");
}
else if($(document).scrollTop() >= 8){
//If you want to get style permenent remove line below
$("div").removeClass("active");
$("#home").addClass("active");
}
});
})
/*This is for smooth scrolling*/
html {
scroll-behavior: smooth;
}
.big {
height: 500px;
width: 100%;
border: solid black 1px;
}
.active {
color:red;
}
<div id="main">
<div style="position:fixed;display:flex;justify-content:flex-end;width:100%">
<p id="demo">0</p>
Home
About Us
Contacts
</div>
<div class="big" id ="home">Home</div>
<div class="big" id ="about">About Us</div>
<div class="big" id ="contacts">Contacts</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Scroll bound hide header on scroll down and vice versa

I have a simple javascript problem that I can't seem to solve.
I want to make a header that hides on scroll down and shows on scroll up, but not with a simple trigger that goes from 0 to 100 on a threshold, but instead I want it to be bound to the scroll. Example: http://oma.eu/
Any ideas?
You can easily do that with Headroom.js: https://wicky.nillia.ms/headroom.js/
You cannot do that in pure javascript without checking the pageYOffset of the window, there is a simple example on w3schools website, see the demo here:
How To Hide Navbar on Scroll Down
UPDATED:
below is a demo of the updated fix (using css transform translateY to set the position of the header):
Demo solution
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
background-color: #f1f1f1;
font-family: Arial, Helvetica, sans-serif;
}
#navbar {
background-color: #333;
position: fixed;
top: 0;
width: 100%;
display:block;
transition: top 0.3s;
}
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 15px;
text-decoration: none;
font-size: 17px;
}
#navbar a:hover {
background-color: #ddd;
color: black;
}
</style>
</head>
<body>
<div id="navbar">
Home
News
Contact
</div>
<div style="padding:15px 15px 2500px;font-size:30px;margin-top:30px;">
<p><b>This example demonstrates how to hide a navbar when the user starts to scroll the page.</b></p>
<p>Scroll down this frame to see the effect!</p>
<p>Scroll up to show the navbar.</p>
<p>Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<script>
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("navbar").style.transform = "translate(0px, 0px)";
} else {
document.getElementById("navbar").style.transform = "translate(0px, -30px";
}
prevScrollpos = currentScrollPos;
}
</script>
</body>
</html>

javascript get current distance of element from div top

I am trying to program a little script which should change the active tab when the offset of the current section is <= 0. I am running a function on every scroll event which should get the distance of every section in the body and calculate the current distance - if the distance is 0, it should be updated and the appropriate element should be set active.
I searched the web and found this solution - however the distance does not change and stays the same.
function scrollPage() {
var sections = document.getElementsByTagName('section');
for (var i = 0; i < sections.length; i++) {
console.log(sections[i].offsetTop - document.body.scrollTop);
}
}
html {
width: 100%;
}
body {
height: 100%;
margin: 0;
}
.body {
position: absolute;
height: auto;
width: auto;
padding-top: 32px;
padding-bottom: 8px;
margin: 48px 0 72px 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow-y: scroll;
}
<html>
<body>
<div class="body" onscroll="scrollPage()">
<section id="section1">
<h1>Text</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</section>
<section id="section2">
<h1>Other text</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</section>
</div>
</body>
</html>
I know that there are ways to do this with JQuery - however I would like to avoid using JQuery so I would be happy if somebody can point out my error.
Best regards and thank you in advance,

clickable rollover image to show text box

I have 3 rollover image that i want to use it as a trigger to show text box under each images. Whenever I try to click it disappears and does not works. I'm trying to make the first one work at least.
here's my code and webpage.
http://yunjinkimdesign.com/question/practice_div.html?
the image showed on snippet is just sample I brought from google...snippet and my actual sample is different
$('.top').on('click', function() {
$parent_box = $(this).closest('.box');
$parent_box.siblings().find('.bottom').hide();
$parent_box.find('.bottom').toggle();
});
img{
width: 200px;
border-radius: 50%;
}
div{
margin: 20px;
}
.container .box .top {
padding: 12px;}
.container .box .bottom {
padding: 12px;
background-color: red;
color: white;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="top">
<img src="http://r.ddmcdn.com/s_f/o_1/cx_633/cy_0/cw_1725/ch_1725/w_720/APL/uploads/2014/11/too-cute-doggone-it-video-playlist.jpg" onmouseover="this.src='https://static.pexels.com/photos/7720/night-animal-dog-pet.jpg'" onmouseout="this.src='http://r.ddmcdn.com/s_f/o_1/cx_633/cy_0/cw_1725/ch_1725/w_720/APL/uploads/2014/11/too-cute-doggone-it-video-playlist.jpg'">
</div>
<div class="bottom">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
You have given href=? in the anchor, Just replace the ? to # or remove href attribute from anchor and your code will run as you want.
<img src="lib/2.png" onmouseover="this.src='lib/papa.jpg'" onmouseout="this.src='lib/2.png'">
$('.top').on('click', function() {
$parent_box = $(this).closest('.box');
$parent_box.siblings().find('.bottom').hide();
$parent_box.find('.bottom').toggle();
});
img {
width: 200px;
border-radius: 50%;
}
div {
margin: 20px;
}
.container .box .top {
padding: 12px;
}
.container .box .bottom {
padding: 12px;
background-color: red;
color: white;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="top">
<a href="#">
<img src="http://r.ddmcdn.com/s_f/o_1/cx_633/cy_0/cw_1725/ch_1725/w_720/APL/uploads/2014/11/too-cute-doggone-it-video-playlist.jpg" onmouseover="this.src='https://static.pexels.com/photos/7720/night-animal-dog-pet.jpg'" onmouseout="this.src='http://r.ddmcdn.com/s_f/o_1/cx_633/cy_0/cw_1725/ch_1725/w_720/APL/uploads/2014/11/too-cute-doggone-it-video-playlist.jpg'">
</a>
</div>
<div class="bottom">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>

Categories

Resources