Three cases on scroll - function inside an if - javascript

I need to set three different background on a navbar:
1. No background if the page is less than 400 px of scrolling
2. Two different colors if the scroll of the page is more than 400 px:
a) blue when I scroll down
b) green when I scroll up.
I've tried to use the following code, but it seems like after I enter in the first IF, the function continue to work even if the page is less than 400px.
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("nav1").style.background = "rgba(0, 41, 51,1)";
} else {
lastScroll = currentScroll;
document.getElementById("nav1").style.background = "rgba(68,78,36,1)";
}
prevScrollpos = currentScrollPos;
} else {
document.getElementById("nav1").style.background = "rgba(0,0,0,0)";
}
}
Thanks!

Do not attempt to assign two functions to window.onscroll, which is a property and can hold only one function.
Here is what is going on with your current code:
An annonymous function is declared (it calls scrollFunction) and assigned to window.onscroll
At the very first scroll, scrollFunction is called. If the page has not scrolled yet beyond 400px, the if block is not executed.
As soon as the page goes beyond 400px, prevScrollpos is declared... Then the function previously assigned to window.onscroll is overwriten with a new one.
That is why the comparison for 400px isn't done after that. It is out of that second function. The first one got lost in the nothingness.
Here is what you want to achieve:
// This variable needs to be global
let prevScrollpos = 0;
// This getElement can also be global
let nav1 = document.getElementById("nav1")
function scrollFunction() {
// This varable needs to be local
let currentScrollPos = window.pageYOffset;
if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
// Determine scroll direction
if (prevScrollpos > currentScrollPos) {
nav1.style.background = "rgba(0, 41, 51,1)";
} else {
nav1.style.background = "rgba(68,78,36,1)";
}
}
// If below 400px
else {
nav1.style.background = "rgba(0,0,0,0)";
}
// Update this variable for the next iteration
prevScrollpos = currentScrollPos;
// For this demo only
console.clear()
console.log(currentScrollPos)
}
// Assign the scrollFunction reference to the window property
window.onscroll = scrollFunction;
body {
height: 1000px;
}
#nav1{
position: sticky;
top: 4px;
height: 100px;
border: 1px solid black;
}
<div id="nav1"></div>

You can use this script:
<script>
window.onscroll = function () { myFunction() };
function myFunction() {
if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
var lastScrollTop = 0;
window.addEventListener("scroll", function () {
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop) {
document.getElementById("nav").style.background = "rgba(0, 41, 51,1)";
} else {
document.getElementById("nav").style.background = "rgba(68,78,36,1)";
}
lastScrollTop = st <= 0 ? 0 : st;
}, false);
} else {
document.getElementById("nav").style.background = "rgba(0,0,0,0)";
}
}
</script>

Related

How to merge two javascript codes into one?

Both scripts work separately but I'm trying to merge them into one. All my efforts didn't work.
It's a simple script to hide the navbar on scroll-down, and show it up on scroll-up with a white background. But when the page is scrolled all the way up, I need the navbar background to become transparent.
<script>
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-85px";
}
prevScrollpos = currentScrollPos;
}
</script>
<script>
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 85 || document.documentElement.scrollTop > 85) {
document.getElementById("navbar").style.background = "#fff";
} else {
document.getElementById("navbar").style.background = "none";
}
}
</script>
There are two ways to solve your problem:
Solution 1: Use window.addEventListener to avoid overriding window.onscroll property
This solution requires the least amount of effort, as it is simply switching out the method of listening to the scroll event. It is also helpful if both logic reside in separate files and you don't want to combine them.
<script>
let prevScrollpos = window.pageYOffset;
window.addEventListener('scroll', () => {
const currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-85px";
}
prevScrollpos = currentScrollPos;
});
</script>
<script>
window.addEventListener('scroll', scrollFunction);
function scrollFunction() {
if (document.body.scrollTop > 85 || document.documentElement.scrollTop > 85) {
document.getElementById("navbar").style.background = "#fff";
} else {
document.getElementById("navbar").style.background = "none";
}
}
</script>
Solution 2: Combine logic from both functions into one
This method moves all your scroll-related logic into a single event listener for the ease of maintenance. In this case, you can still use window.onscroll to assign the function, even though I would strongly encourage not to do so:
<script>
window.addEventListener('scroll', () => {
navBarScrollFunction();
scrollFunction();
});
let prevScrollpos = window.pageYOffset;
function navBarScrollFunction() {
const currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-85px";
}
prevScrollpos = currentScrollPos;
}
function scrollFunction() {
if (document.body.scrollTop > 85 || document.documentElement.scrollTop > 85) {
document.getElementById("navbar").style.background = "#fff";
} else {
document.getElementById("navbar").style.background = "none";
}
}
</script>

Hidden Javascript Button on larger screen

I am new to Javascript but have the following code taken from W3 How to Scroll Back to Top Button: https://www.w3schools.com/howto/howto_js_scroll_to_top.asp
I'd like to remove the button on a min-width media query (for example min-width:600px) - is that possible? Sorry, I am sure this is really basic, thanks.
Code
var mybutton = document.getElementById("top-button");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
#top-button {
display: none;
position: fixed;
bottom: 0.75rem;
right: 0.75rem;
z-index: 99;
background-color: #1A936F;
color: #f3e9d2;
cursor: pointer;
padding: 0.75rem;
border-radius: 0.5rem;
font-size: 1.1rem;
}
<button onclick="topFunction()" id="top-button" title="Go to top">Top</button>
Use window.innerWidth property.
Something like,
window.onscroll = function() {
if (window.innerWidth <= 600) {
scrollFunction();
}
};
Sample: https://jsfiddle.net/codeandcloud/sezk0j74/
var mybutton = document.getElementById("top-button");
var x = window.matchMedia("(max-width: 600px)");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (x.matches) {
mybutton.style.display = "none";
}
else if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20){
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
Here, This should work!
Basically, you can use window.matchMedia("(max-width: 600px)").matches to check screen size. Then you can add js code to make button display none.

i am adding page-scroller-loader like a horizontal line and top scroll button to going on top of website with help of javascript

When page-scroller-loader works, top scroll button stop working and when top scroll button works page-scroller-loader don't work.
Here javascript code below:
// When the user scrolls the page, execute myFunction
window.onscroll = function () { myFunction() };
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
// =================Top button========
//Get the button
var mybutton = document.getElementById("myBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function () { scrollFunction() };
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// ==================================Top Button End=====================

Javascript in Footer Not Loading in Wordpress

I have the following code for hiding and showing a navigation bar on my Wordpress website:
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$("#pn-navigation-bar").fadeIn();
} else {
$("#pn-navigation-bar").fadeOut();
}
});
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos < currentScrollPos) {
document.getElementById("pn-navigation-bar").style.opacity = 0;
document.getElementsByClassName("readingProgressbar")[0].style.display = "block";
} else if (prevScrollpos > currentScrollPos) {
document.getElementById("pn-navigation-bar").style.opacity = 1;
document.getElementsByClassName("readingProgressbar")[0].style.display = "none";
}
prevScrollpos = currentScrollPos;
};
And the following CSS to prevent it from loading the first time the page loads:
#pn-navigation-bar {
position: fixed;
top: 0;
width: 100%;
transition: all .3s ease-in-out;
display: none;
}
Ideally, this should be hiding the Navigation bar shown below while the user scrolls down and show it when a scroll up is detected.
However, as you can see if you visit the website here, this does not happen. This was working fine till a few days ago, but I don't know what has gone wrong. I've been optimizing my website for speed (JS/CSS minification) but I doubt that this gets affected. What can I do to fix this?
As suggested by users #mplungjan and #Howard E, Wordpress runs jQuery.noConflict. To prevent conflict with other JS librares, Wordpress will not recognize $ to be JQuery code and usually expects Jquery in place of the traditional $
To fix this, the easiest way is to map $ to JQuery.
According to this article, The code for this is:
(function($) {
//Insert Code Here
})( jQuery );
To correct the error, the code becomes:
<script>
(function($) {
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$("#pn-navigation-bar").fadeIn();
} else {
$("#pn-navigation-bar").fadeOut();
}
});
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos < currentScrollPos) {
document.getElementById("pn-navigation-bar").style.opacity = 0;
document.getElementsByClassName("readingProgressbar")[0].style.display = "block";
} else if (prevScrollpos > currentScrollPos) {
document.getElementById("pn-navigation-bar").style.opacity = 1;
document.getElementsByClassName("readingProgressbar")[0].style.display = "none";
}
prevScrollpos = currentScrollPos;
};
})( jQuery );
</script>

stop scrolling div from overlapping footer

Is there a way to have the div called #middlecta stop scrolling when it reaches #footer?
FIDDLE:
http://jsfiddle.net/BP6rq/1522/
var pointOne = $("#form").offset().top;
$(window).on("scroll", function () {
$.fx.speeds.xslow = 750;
if ($(this).scrollTop() > pointOne) {
$("#middlecta").fadeIn('xslow').addClass('fixed');
} else {
$("#middlecta").fadeOut('xslow').removeClass('fixed').hide();
}
$("#middlecta-t").addClass("mob");
});
You definitely want to play around with the CSS. Setting a 100px margin may or may not be a good idea. But, this should get you thinking on the right track at least.
var pointOne = $("#form").offset().top;
var pointTwo = $('#footer').position().top;
var $midCta = $("#middlecta");
$(window).on("scroll", function () {
$.fx.speeds.xslow = 750;
if ($(this).scrollTop() > pointOne) {
$midCta.fadeIn('xslow').addClass('fixed');
} else {
$midCta.fadeOut('xslow').removeClass('fixed').hide();
}
if ($midCta.offset().top > pointTwo) {
$midCta.css('bottom', 150);
$midCta.fadeOut('xslow').removeClass('fixed');
}
$midCta.addClass("mob");
});
http://jsfiddle.net/BP6rq/1523/

Categories