Sticky navbar working on jsfiddle, but not as expected on localhost - javascript

I've put together a sticky navbar that appears after 10px in a relative position, and then becomes fixed once it scrolls past offset().top.
This works as desired on the fiddle, but on localhost (with the exact same code) the navbar is fixed as soon as it appears (it ought to be relatively positioned till the offset point, as demonstrated in the fiddle).
Would appreciate any insight on why it's behaving different on the localhost?
Also, I've added jquery (<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>) and there are no console errors.
Here is the javascript as i'm running it from the localhost:
<script type="text/javascript">
document.getElementById('navig').style.visibility = 'hidden';
var fixed = false;
var topTrigger = $('#navig').offset().top;
$(window).scroll(function () {
if ($(this).scrollTop() > 10) {
document.getElementById('arr_downpoint').style.visibility = 'hidden';
document.getElementById('navig').style.visibility = 'visible';
}
else {
document.getElementById('arr_downpoint').style.visibility = 'visible';
document.getElementById('navig').style.visibility = 'hidden';
}
});
$(document).scroll(function() {
if( $(this).scrollTop() >= topTrigger ) {
if( !fixed ) {
fixed = true;
$('#navig').css({'position':'fixed', 'top':'0'});
}
} else {
if( fixed ) {
fixed = false;
$('#navig').css({'position':'relative'});
}
}
});
</script>

Try wrapping everything inside your <script> tag into $(document).ready() function:
$(function () {
document.getElementById('navig').style.visibility = 'hidden';
var fixed = false;
var topTrigger = $('#navig').offset().top;
$(window).scroll(function () {
if ($(this).scrollTop() > 10) {
document.getElementById('arr_downpoint').style.visibility = 'hidden';
document.getElementById('navig').style.visibility = 'visible';
}
else {
document.getElementById('arr_downpoint').style.visibility = 'visible';
document.getElementById('navig').style.visibility = 'hidden';
}
});
$(document).scroll(function() {
if( $(this).scrollTop() >= topTrigger ) {
if( !fixed ) {
fixed = true;
$('#navig').css({'position':'fixed', 'top':'0'});
}
} else {
if( fixed ) {
fixed = false;
$('#navig').css({'position':'relative'});
}
}
});
});

Related

Event on scrolling up or down

I wanna detect when the user scrolls. I saw there are some questions about this but those answers didn't help me.
Here is my code:
var up = document.getElementById('up');
var down = document.getElementById('down');
function onScroll() {
if (view.scrollTop > 0) {
console.log("up");
}
if (view.scrollTop < 0) {
console.log("down");
}
}
var view = document.getElementById('container');
view.addEventListener("wheel", onScroll);
EDIT: "scroll" instead "wheel" isn't working for me... I must have the "wheel". When I make:
if (view.scrolltop <=0) {
console.log("down");
}
that I get in my console "down" but it appears when I scrolling up too! I have my page in 100% of screen and I have no scrollbars (and I don't want to have).
EDIT2: Here is the code that solved my problem!
window.addEventListener('wheel', function (e) {
if (e.deltaY < 0) {
console.log("scrolling up");
}
if (e.deltaY > 0) {
console.log("scrolling down");
}
});
you can use the
window.onscroll
to get the scrolling event, then just use
.scrollTop
to determine your offset from the top of page or an element.
window.onscroll = function() { scrollFunction() };
scrollFunction() {
//code to check if it is scrolling up or down
}
Hopefully this was a helpful start.
I did this with the jquery method
var last = 0;
$(window).scroll(function(event){
var Pos = $(this).scrollTop();
if (Pos > last ){
// down
} else {
// up
}
last = Pos;
});
Supporting #Belmin Bedak's comment.
Use .scroll instead of .wheel:
var up = document.getElementById('up');
var down = document.getElementById('down');
function onScroll() {
if (view.scrollTop > 0) {
alert("up");
}
if (view.scrollTop <= 0) {
alert("down");
}
}
var view = document.getElementById('container');
view.addEventListener("scroll", onScroll);
div {
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
<div id='container'>a<br>
b<br>
c<br>
d<br>
e<br>
f<br>
g<br>
h<br>
i<br>
k<br>
l<br>
</div>

jQuery toggle not working on resize

When I resize the window, the toggle part is not working, I had to refresh the page again(keeping the window in the resized state) and it works fine.
bodyClass() part is working fine, just not the menu() part.
Please help :)
jQuery(document).ready(function() {
function menu(){
var memberAreaWidth = jQuery(window).width();
if( memberAreaWidth <= 900 ){
jQuery('.memebers-menu').css('display', 'none');
jQuery('.memebers-header-logo span').click(function(){
jQuery('.memebers-menu').toggle();
});
}
}
function bodyClass(){
var memberAreaWidth = jQuery(window).width();
if( memberAreaWidth > 900 ){
jQuery('body').addClass('fullwidth');
}else{
jQuery('body').removeClass('fullwidth');
}
}
jQuery(window).on("load resize",function(){
menu();
bodyClass();
});
});
Move the click event delegation so it only happens once. The rest of the code looks fine.
var smallWidth = false;
jQuery('.memebers-header-logo span').click(function(){
if (smallWidth){
jQuery('.memebers-menu').toggle();
}
});
function menu(){
var memberAreaWidth = jQuery(window).width();
if( memberAreaWidth <= 900 ){
jQuery('.memebers-menu').css('display', 'none');
smallWidth = true;
} else {
smallWidth = false;
}
}
Simplify your code a bit, put the event handlers outside the functions so they do not re-bind each time the function is called (which would end up with multiple event handlers firing); pass a parameter so you only have to calculate it once.
jQuery(document).ready(function() {
jQuery('.memebers-header-logo span').on('click', function() {
jQuery('.memebers-menu').toggle();
});
jQuery(window).on("load resize", function() {
var memberAreaWidth = jQuery(window).width();
menu(memberAreaWidth);
bodyClass(memberAreaWidth);
});
function menu(memberAreaWidth) {
if (memberAreaWidth <= 900) {
jQuery('.memebers-menu').hide();
}
}
function bodyClass(memberAreaWidth) {
if (memberAreaWidth > 900) {
jQuery('body').addClass('fullwidth');
} else {
jQuery('body').removeClass('fullwidth');
}
}
});

Use function everywhere without writing it more than once

Trying to get my code cleaner I don't want to write the same code many times but don't know how to accomplish it. You can see in the code below is the if/else written twice but doing the same. How can I return data and call that function again with writing it only once?
Help and advices are much appreciated.
Code is like this:
(function($){
var scroll = $(this).scrollTop();
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
var showNav = function() {
header.css('position','fixed');
headerBigWrap.css('display','none');
headerSmall.css('display','block');
}
var hideNav = function() {
header.css('position','static');
headerSmall.css('display','none');
headerBigWrap.css('display','block');
}
// don't want to write this more than once
// but need to call here on document ready
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
$(window).scroll(function(event){
scroll = $(this).scrollTop();
// here I need it again
// scroll is changing on scroll
// but "function" does exactly the same like above
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
});
})(jQuery);
if you need html and css working example: fiddle http://jsfiddle.net/cejs3jhs/ and rest of code:
<header>
<div class="big">
<h1>Page Title</h1>
</div>
<div class="small">
<span class="icon nav-icon">Nav Icon</span>
</div>
</header>
<div class="page"></div>
<style type="text/css">
header {
width:100%;
background-color:red;
opacity:0.5;
}
header.toggle-nav {
height:100%;
}
header.toggle-nav ul {
display:block;
}
header > div {
position:relative;
width:976px;
margin:0 auto;
}
header > div.big {
padding:30px 0;
}
.page {
height:5000px;
background-color:orange;
opacity:0.5;
}
</style>
So just make separate function for that:
function showHideNav(scroll, headerBigWrapHeight, element) {
var scroll = element.scrollTop(),
header = $('header'),
headerSmall = header.children('.small'),
headerBigWrap = header.children('.big')
headerBigWrapHeight = headerBigWrap.height();
if( scroll >= headerBigWrapHeight ) {
header.css('position','fixed');
} else {
header.css('position','static');
}
headerBigWrap.toggle();
headerSmall.toggle();
}
(function($){
showHideNav(scroll);
$(window).scroll(function(event){
scroll = $(this).scrollTop();
showHideNav(scroll);
});
})(jQuery);
The answer to your question is simply what Justinas said, make another function. But you can improve a bit with some more aggressive editing, which is what I've done.
(function ($) {
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
function setNavStyle() {
var scroll = $(this).scrollTop();
if( scroll >= headerBigWrapHeight ) {
header.css('position', 'fixed');
headerSmall.css('display', 'block');
headerBigWrap.css('display', 'none');
} else {
header.css('position', 'static');
headerSmall.css('display', 'none');
headerBigWrap.css('display', 'block');
}
}
$(window).scroll(setNavStyle);
setNavStyle();
})(jQuery);
That's one way, but it would be better (more maintainable, simpler, faster) to do the bulk of
the work with CSS, like so:
CSS:
header {
position: static;
}
header>.small {
display: none;
}
header>.big {
display: block;
}
.stickyNav header {
position: fixed;
}
.stickyNav header>.small {
display: block;
}
.stickyNav header>.big {
display: none;
}
JavaScript:
(function ($) {
var bigNavHeight = $('header>.big').height();
function setNavStyle() {
var bigIsOffscreen = $(this).scrollTop() >= bigNavHeight;
$(document.body).toggleClass('stickyNav', bigIsOffscreen);
}
$(window).scroll(setNavStyle);
setNavStyle();
})(jQuery);
You can define a new function just as you did with the showNav & hideNav functions
(function($){
var scroll = $(this).scrollTop();
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
var showNav = function() {
header.css('position','fixed');
headerBigWrap.css('display','none');
headerSmall.css('display','block');
}
var hideNav = function() {
header.css('position','static');
headerSmall.css('display','none');
headerBigWrap.css('display','block');
}
var checkScroll = function (scroll,headerBigWrapHeight){
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
checkScroll(scroll,headerBigWrapHeight);
$(window).scroll(function(event){
scroll = $(this).scrollTop();
checkScroll(scroll,headerBigWrapHeight);
});
})(jQuery);
Please find below updated JS code:
(function($){
var scroll = $(this).scrollTop();
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
var showNav = function() {
header.css('position','fixed');
headerBigWrap.css('display','none');
headerSmall.css('display','block');
}
var hideNav = function() {
header.css('position','static');
headerSmall.css('display','none');
headerBigWrap.css('display','block');
}
var callFun = function(scroll) {
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
}
callFun(scroll);
$(window).scroll(function(event){
scroll = $(this).scrollTop();
callFun(scroll);
});
})(jQuery);
Do it exactly like you have done with functions showNav and hideNav: define a function with if/else inside somewhere and you can call it by name wherever needed. There are also some variables which can be omitted then, so I show all code here:
(function($){
// var scroll is moved into function scrollFunc
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
// var headerBigWrap is moved into function scrollFunc
var showNav = function() {
/* your code */
}
var hideNav = function() {
/* your code */
}
var scrollFunc = function () {
if($(this).scroll() >= headerBigWrap.height() ) {
showNav();
} else {
hideNav();
}
}
$(window).scroll(function(event){
scrollFunc();
});
scrollFunc(); // call it first time to initialize
});

Prevent scrolling jquery script from running twice

I'm new to jquery and have put together the following code to make a DIV appear after a set scroll-down amount. If scrolling back up, the DIV disappears. Optionally, once the DIV has appeared, there is a link to close it. This all works as intended, apart from that I only want the script to run once. At the moment if I scroll back up, the yellow box appears again. How can I ensure the box stays closed? As another option, could I integrate cookies or localStorage?
Many thanks! Russ.
Javascript:
$(function () {
var target = $(".box");
if ($(window).scrollTop() > 30) {
target.hide();
}
$(window).scroll(function () {
var pos = $(window).scrollTop();
if (pos > 30) {
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
}
});
$('a.close').click(function () {
$($(this).attr('href')).slideUp();
return false;
});
});
Here is the jsfiddle link to my code: jsfiddle link
You can remove the class to ensure the box stays enclosed with removeClass(). Or directly $(".box").remove() after your animation.
You can store this choice with cookie but if the client deletes his cookies, it's lost.
You can remove event scroll from window and for localStorage do something like that:
$(function () {
var target = $(".box");
if ($(window).scrollTop() > 30) {
target.hide();
}
$(window).scroll(function () {
var pos = $(window).scrollTop();
if (pos > 30) {
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
}
if(localStorage['noNotification'] == 'true'){
$(window).off('scroll');
}
});
$('a.close').click(function () {
$($(this).attr('href')).slideUp();
$(window).off('scroll');
localStorage['noNotification'] = 'true';
return false;
});
});
try this http://jsfiddle.net/AbwXu/4/
var notdisplayed=true;
$(function(){
var target = $(".box");
if($(window).scrollTop() > 30){
target.hide();
}
$(window).scroll(function(){
var pos = $(window).scrollTop();
if(pos > 30 && notdisplayed){
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
notdisplayed=false;
}
});
$('a.close').click(function() {
$($(this).attr('href')).slideUp();
notdisplayed=false;
return false;
});

Style element with javascript

I am trying to make a gototop button with javascript (not jQuery).
I want this button to have a delay effect which I achieve by:
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
The html is a simple:
<div id="gototop">Back to top</div>
I am not able to make to button show/hide depending on scroll height. As far as I have been able to find out, the following should hide the button from view until the page has been scrolled down 600px, but this does not work:
var posit = window.scrollTop();
if (posit < 900) {
document.getElementById("gototop").style.display = 'none';
}
Why does this styling not take effect?
The complete code I am using is:
var posit = window.scrollTop();
if (posit < 900) {
document.getElementById("gototop").style.display = 'none';
}
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
Thanks for your attention, greetings.
Try putting it into the onscroll event handler, like:
Add style to your gototop element, for example:
<div id="gototop" onclick="scrollToTop()" style="display:none;"> </div>
window.onscroll = function(){
if (window.scrollY < 900) {
document.getElementById("gototop").style.display = 'none';
else
document.getElementById("gototop").style.display = 'block';
}
This is the complete working code for a Back-to-top button.
<style type="text/css">
#gototop{display:none;position:fixed;right:28px;bottom:10px;z-index:100;}
#gototop a{font-size:14px;font-weight:bold;display:block;padding:5px;text-decoration:none;color:#fff;background:#000;opacity:0.5;border:1px solid #aaa;}
#gototop a:hover{color: #000;text-decoration:underline;background-color:#fff;border: 2px solid #aaa;opacity:0.5;}
</style>
<script type="text/javascript" language="javascript">
// document.documentElement.scrollTop makes it work in Chrome and IE
// 400 is the point from which the button starts showing, you can change it to your needs
gototop = document.getElementById("gototop");
window.onscroll = function(){
if (window.scrollY < 400 || document.documentElement.scrollTop < 400) {
gototop.style.display = 'none';
}
if (window.scrollY > 400 || document.documentElement.scrollTop > 400)
gototop.style.display = 'block';
}
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
</script>
<div id="gototop">Back to Top</div>

Categories