Javacript for Navbar - javascript

Im creating a navbar. The add javascript to it for two functions. One, the navbar will go invisible when the user scrolls down. Second, the invisible navbar will be visible again if the user reaches the end of the webpage or if they scroll up midway.I can't find the problem in my code, will be helpful if anyone can point it out for me
/ select the navbar element
var navbar = document.getElementById("navbar");
// set a variable to track the previous scroll position
var prevScrollpos = window.pageYOffset;
// listen for scroll events on the window
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
// check if the user has scrolled down
if (prevScrollpos > currentScrollPos) {
navbar.style.top = "0";
} else if (currentScrollPos + window.innerHeight >= document.body.offsetHeight) {
// check if the user has reached the bottom of the page
navbar.style.top = "0";
} else {
navbar.style.top = "-50px";
}
prevScrollpos = currentScrollPos;
};

The code you provided seems to be on the right track for creating a navbar with the functionality you described. The navbar element is selected, and the onscroll event is being used to track the user's scroll position and make the navbar visible or invisible based on that position.
The main issue I see is that you're using the navbar.style.top property to change the visibility of the navbar. It's better to use a class to change the visibility of the navbar, so you can add CSS styles to control the transition.
You can create a class like "navbar-invisible" and then add and remove the class to the navbar element to change its visibility.
// select the navbar element
var navbar = document.getElementById("navbar");
// set a variable to track the previous scroll position
var prevScrollpos = window.pageYOffset;
// listen for scroll events on the window
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
// check if the user has scrolled down
if (prevScrollpos > currentScrollPos) {
navbar.classList.remove("navbar-invisible");
} else if (currentScrollPos + window.innerHeight >= document.body.offsetHeight) {
// check if the user has reached the bottom of the page
navbar.classList.remove("navbar-invisible");
} else {
navbar.classList.add("navbar-invisible");
}
prevScrollpos = currentScrollPos;
};
.navbar-invisible {
top: -50px;
transition: top 0.3s ease-in-out;
}
It is important to test this code in different browsers, since browser compatibility can sometimes be an issue when working with JavaScript.

Related

element.style loading whenever the page is loaded but it is supposed to function on window.onscroll

I am trying to make a web page in which the top nav bar hides on scrolling down and shows up on scrolling up. I am using the code given below to do so.
<nav class="navbar navbar-expand-lg navbar-dark navbar-custom fixed-top" id='navHeader'>
<!-- all the elements of navbar like logo and menu goes here-->
</nav> <!-- end of navbar -->
<!-- end of navigation -->
<script>
var header=document.getElementById("navHeader");
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
navHeader.style.top = "0";
} else {
navHeader.style.top = "-50px";
}
prevScrollpos = currentScrollPos;
}
</script>
But the problem is the element.style should load on scrolling the web page sown. But it is loading initially when the web page is opened and the nav bar is not visible initially. When the web page is scrolled down and then up again at that time the nav bar is visible.
The Images Given below may also help you
Initally and on scrolling down
On scrolling up
But when the page loaded for first time and untill and unless it is scrolled there should not be any element.style I guess.
Then Why is this happening and how can is I solve it.
Thanks for any help in Advance.
I think this is quite simple: just add this code right before the scroll event
navHeader.style.top = "0";
some thing like this:
<script>
var header=document.getElementById("navHeader");
navHeader.style.top = "0";//Please add this new line
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
navHeader.style.top = "0";
} else {
navHeader.style.top = "-50px";
}
prevScrollpos = currentScrollPos;
}
</script>
The main problem I see is that you're setting the variable header to the element with the id navHeader, but then you're trying to set the style on the navHeader variable, which you haven't defined. Does it work if you change those references to header instead?

How do I code JQuery so that when I scroll to a certain element, Nav bar appears at top, when I scroll back up past that element, nav bar disappears

I have a div called #menu which I want to display when I scroll past the element #section3, if I scroll up past that element again, I want #menu to disappear
How would I code this?
Maybe something like this?
scrolled = "no"
$(window).scroll(function(){
scr = $("body").scrollTop();
if (scr > 100 && scrolled == "no"){
$("#menu").css({"display:block"})
displayed = "yes"
}
if (displayed == "yes" && scrolled = "yes"){
$("#menu").css({"display:none"})
}
});
The above assumes that #section3 is 100 pixels down the page. If you do not know where its going to be on the page then you could use the method outlined here:
Trigger event when user scroll to specific element - with jQuery
With jQuery you can get the scroll position with $("body").scrollTop();.
Expanding on what #Ned Hulton said, I recommend comparing the scroll position to the top of a "container element" (or 'row') in your page like this:
if ($('body').scrollTop() > $('#someRow').offset().top){
//do something
}
That way you can account for your container appearing at a variable distance down the page (which will come in handy for mobile browsing or cases where your text wraps to additional lines)
I just whipped this up in jsfiddle
https://jsfiddle.net/rb56j0yu/
it uses jQuery, and checks the scroll position against the target div. Css sets the menu as position: fixed, and defaults to hidden.
$(window).scroll(function(){
var yPos = $("body").scrollTop();
var yCheck = $("#c3").position().top;
if (yPos > yCheck && !$("#menu").is(":visible"))
{
$("#menu").show();
}
if (yPos <= yCheck && $("#menu").is(":visible"))
{
$("#menu").hide();
}
});
First, get your #section3 top offset and height. Which will be used as the threshold whether #section3 is actually on the window screen.
var top = $('#section3').offset().top;
var bot = topOffset + $('#section3').height();
Then, detect it on your scroll event.
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop >= top && scrollTop <= bot) {
// #section3 is within the screen.
$('#menu').show();
}
else {
// #section3 is out of screen.
$('#menu').hide();
}
});
This is a common use case, I wrote following code:
// what does "Auto Header" mean, goto https://www.yahoo.com/
// scroll down and you will see the purple part auto fixed to top,
// while when scroll up, it restores and does not be fixed.
// 1. multiple auto header elements handled
// 2. dynamically create/remove elements issue handled
// 3. no unnecessary dom operation, high performance
// usage: just add 'class="auto-header"' to any element you want to auto header
// suggest set each auto-header element specific width and height
// do not guarantee it works when resize or scroll left/right
$(document).ready(function() {
var rawTops = [],
rawLefts = [],
rawStyles = [],
$locations = [], // record next sibling so that element easily find where to restore
fixed = []; // mark whether this element is fixed
$(".auto-header").each(function() {
var $this = $(this),
offset = $this.offset();
rawTops.push(offset.top);
rawLefts.push(offset.left);
rawStyles.push($this.attr("style"));
$locations.push($this.siblings().eq($this.index()));
fixed.push(false);
});
$(window).on("scroll", function() {
$(".auto-header").each(function(i, e) {
if(!fixed[i] && $(window).scrollTop() > rawTops[i]) {
var $te = $(this).clone(true);
$(this).remove();
$locations[i].before($te);
$te.css({
"position": "fixed",
"top": 0,
"left": rawLefts[i],
"z-index": 100
});
fixed[i] = true;
} else if(fixed[i] && $(window).scrollTop() < rawTops[i]) {
$(this).removeAttr("style").attr("style", rawStyles[i]);
fixed[i] = false;
}
});
});
});

Show div after scrolled back to the top

I want to show a Top-Bar, when the user scrolled back to top of the site.
So e.g. the user scrolls down for a minimum of a 300-400px and then when he scrolls back up again to maybe around 100px (left to the top of the site) the bar should toggle / show up.
Thanks for your help! :)
You can add an event listener to document to check when a user scrolls down the page. Once they hit a preset breakpoint, you can remove a hidden class from your navbar element, like so:
var breakpoint = 400;
var navbar = $('.nav-bar');
$(document).scroll(function(){
if($(this).scrollTop() >= breakpoint) {
navbar.removeClass('hidden', 500);
}
});
If your navbar is fixed, you can also check a boolean variable to see if the user has scrolled past the breakpoint, and then set it to true. If they scroll up past the breakpoint, you can then show the navbar, like so:
var breakpoint = 400;
var scrolledPastBreakpoint = false;
var navbar = $('.nav-bar');
$(document).scroll(function(){
if($(this).scrollTop() >= breakpoint) {
scrolledPastBreakpoint = true;
};
if($(this).scrollTop() < breakpoint && scrolledPastBreakpoint) {
navbar.removeClass('hidden', 500);
};
});

When hiding/showing navigation bar, the nav bar is visible when the page is refreshed then disappears when I scroll

I've created a page where the second nav bar appears when scrolling, and should be hidden when the window is at top: 0. When refreshing the page, the nav bar is visible, and then disappears when scrolling to then appear at the scrollPos set to appear.
How do I make it so that it is hidden when the page is refreshed?
The webpage is www.fareastfestival.com please take a look to help.
Here is the JS code I have used:
$(document).ready(function() {
var navOffset = $("nav1").offset().top;
$("nav").wrap('<div class="nav-placeholder"></div>');
$(".nav-placeholder").height($("nav").outerHeight());
$(window).scroll(function(){
var scrollPos = $(window).scrollTop();
if (scrollPos >= navOffset) {
$("nav").removeClass("hide");
$("nav").addClass("fixed");
$(".navlogo").show();
}
else {
$("nav").addClass("hide");
$("nav").removeClass("fixed");
$(".navlogo").hide();
}
});
});
Just add the .hide class to your HTML element.
Here's an example (line 7):
$(document).ready(function() {
var navOffset = $("nav1").offset().top;
$("nav").wrap('<div class="nav-placeholder"></div>');
$(".nav-placeholder").height($("nav").outerHeight());
$("nav").addClass("hide");
$(window).scroll(function(){
var scrollPos = $(window).scrollTop();
if (scrollPos >= navOffset) {
$("nav").removeClass("hide");
$("nav").addClass("fixed");
$(".navlogo").show();
}
else {
$("nav").addClass("hide");
$("nav").removeClass("fixed");
$(".navlogo").hide();
}
});
});
The above code adds the class dynamically. You could also just added to the HTML.
Add the hide class to nav in your html file like so <nav class="hide">

How can I set my browser window's scrollbar or a div scrollbar to scroll in increments using animate and scrollTop?

The general idea to the site i am designing is to scroll through a set of menu items horizontally and incrementally underneath a static div that will magnify(increase dimensions and pt size) the contents of a menu items. I don't really need help with the magnify portion because i think it's as simple as adding a mag class to any of the menuItem divs that go underneath the static div. I have been messing with this for a few weeks and the code I have for incrementally scrolling, so far, is this:
$(document).ready(function () {
currentScrollPos = $('#scrollableDiv').scrollTop(120); //sets default scroll pos
/*The incrementScroll function is passed arguments currentScrollPos and UserScroll which are variables that i have initiated earlier in the program, and then initiates a for loop.
-The first statement sets up the variables: nextScrollPos as equal to the currentScrollPos(which by default is 120px) plus 240px(the distance to next menuItem), prevScrollPos as equal to the currentScrollPos(which by default is 120px) minus 240px(the distance to next menuItem).
-The second Statement checks to see if the user has scrolled using var userScroll
-The third statement sets: var CurrentScroll equal to the new scroll position and var userScroll to false*/
function incrementScroll(currentScrollPos, userScroll) {
for (var nextScrollPos = parseInt(currentScrollPos + 240, 10),
prevScrollPos = parseInt(currentScrollPos - 240, 10); //end first statement
userScroll == 'true'; console.log('dude'), //end second statement and begining of third
currentScrollPos = scrollTop(), userScroll = 'false') {
if (scrollTop() < currentScrollPos) {
$('#scrollableDiv').animate({
scrollTop: (parseInt(prevScrollPos, 10))
}, 200);
console.log('scrolln up')
} else if (scrollTop() > currentScrollPos) {
$('#scrollableDiv').animate({
scrollTop: (parseInt(nextScrollPos, 10))
}, 200);
console.log('scrolln down')//fire when
}
}
}
$('#scrollableDiv').scroll(function () {
userScroll = 'true';
_.debounce(incrementScroll, 200); //controls the amount of times the incrementScroll function is called
console.log('straight scrolln')
});
});
I have found a variety of solutions that are nigh close: such as a plugin that snaps to the next or previous div horizontally demo, another solution that also snaps and is based on setTimeout demo, but nothing that nails incrementally scrolling through divs. I also found a way to control the rate at which a user may scroll through the menuItems using debounce which is included in the above code.
The console.logs inside the loop do not fire when I demo the code in jsfiddle which leads me to believe the problem lies within the loop. I'm a noob though so it could be in syntax or anywhere else in the code for that matter. Also in the second demo, i have provided the css for the horizontal static div, but the moment I put it in my html it keeps the js from working.
I would like to write the code instead of using a plugin and any help would be appreciated! Also, thank you ahead of time!
Try this fiddle. Menu container height is 960px to show 4 menu items. "Zoom" div is positioned absolutely at top. When you scroll mouse over this div, menu items shifts to top/bottom. I had to add additional div to bottom to be able to scroll to last 3 menu items. JS code:
jQuery(document).ready(function($){
var current = 0;
var menu = $('.menu-container').scrollTop(0);
var items = menu.find('.menu-item');
var zoom = $('.zoom');
function isVerticalScroll(event){
var e = event.originalEvent;
if (e.axis && e.axis === e.HORIZONTAL_AXIS)
return false;
if (e.wheelDeltaX)
return false;
return true;
}
function handleMouseScroll(event){
if(isVerticalScroll(event)){
var delta = event.originalEvent.wheelDelta * -1 || event.originalEvent.detail;
current += (delta > 0 ? 1 : -1);
if(current < 0)
current = 0;
if(current >= items.length){
current = items.length - 1;
}
menu.stop().animate({
"scrollTop": current * 240
}, 300);
items.removeClass('current').eq(current).addClass('current');
event && event.preventDefault();
return false;
}
}
zoom.on({
"MozMousePixelScroll": handleMouseScroll,
"mousewheel": handleMouseScroll
});
});
Hope it will help.

Categories