More than one function on scroll? - javascript

With my current code I can only have one or the other, which is either my sticky navigation or a back to top button that appears at a 100px from the top of the document. Is there any way I can use both?
This is my current code
window.onscroll = function() {navFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function navFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
and
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
sorry if this is a silly question. I am still new to this :)
Thanks in advance!

You can call both functions inside window.onscroll anonymous function:
window.onscroll = function() {
navFunction();
scrollFunction();
};
Alternatively, you can use the standard addEventListener method to register both functions:
window.addEventListener("scroll", navFunction);
window.addEventListener("scroll", scrollFunction);
Notice that in this way we don't use the parentheses with the two functions because we're not executing them. We're just telling the event listener the name of the function that it will execute when the event occurs.

One thing you can do is just reorganize your code to call both functions.
// Define the functions and the variables you need first here
// function topFunction() {...} etc
// call both functions inside the scroll event here.
window.onscroll = function() {
scrollFunction();
navFunction()
};
The other way to run multiple functions on an event is by using addEventListener()
window.addEventListener("scroll",scrollFunction,false);
window.addEventListener("scroll",navFunction,false);
You can keep appending as many functions as you want, though you risk making your web page slower.

window.onscroll = function() {onscroll_function()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function onscroll_function() {
navFunction();
scrollFunction();
//...what ever else you want to trigger
}
function navFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
function scrollFunction() {
if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

Related

My javascript function not working, greyed out

I followed w3 schools guide on how to make a scroll back top top button in your html with javascript. When I put the javascript and html where they should be one of the javascript function didn't work. It got greyed out in vscode and in chrome console it says that the "function is not defined".
This is how it looks in vscode:
I tried rewriteing the code in the html and js but with no luck. I also tried writeing a new function under the "topFunction" function and that also gets greyed out so I don't know whats seems to be the problem.
And this is the whole javascript with html:
https://jsfiddle.net/md5pf3hx/ a jsfiddle with the whole site
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
//Get the button:
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; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
You can't access topFunction because it's declared inside loadScript function.
You need to remove loadScript function
const slider = document.querySelector(".slider");
const nextBtn = document.querySelector(".next-btn");
const prevBtn = document.querySelector(".prev-btn");
const slides = document.querySelectorAll(".slide");
const numberOfSlides = slides.length;
var slideNumber = 0;
//image slider next button
nextBtn.addEventListener("click", () => {
slides.forEach((slide) => {
slide.classList.remove("active");
});
slideNumber++;
if (slideNumber > numberOfSlides - 1) {
slideNumber = 0;
}
slides[slideNumber].classList.add("active");
});
//image slider previous button
prevBtn.addEventListener("click", () => {
slides.forEach((slide) => {
slide.classList.remove("active");
});
slideNumber--;
if (slideNumber < 0) {
slideNumber = numberOfSlides - 1;
}
slides[slideNumber].classList.add("active");
});
//image slider autoplay
var playSlider;
var repeater = () => {
playSlider = setInterval(function() {
slides.forEach((slide) => {
slide.classList.remove("active");
});
slideNumber++;
if (slideNumber > numberOfSlides - 1) {
slideNumber = 0;
}
slides[slideNumber].classList.add("active");
}, 5000);
};
repeater();
//Get the button:
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; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
If you want the script run after the page is loaded you can add defer parameter
<script defer src="script/js.js"></script>
You're issue is you do not have topFunction defined in Global scope. To allow your HTML to have access to invoke topFunction, you can move it outside of the loadScript definition.
function loadScript {
// ...
}
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
However, you should be using the built-in defer attribute of the HTML <script> element to execute JavaScript after your HTML has finished loading.
<script defer src="script/js.js"></script>
This way, you can remove the need for load event listeners and whole-script function wrappers:
const slider = document.querySelector(".slider");
const nextBtn = document.querySelector(".next-btn");
const prevBtn = document.querySelector(".prev-btn");
const slides = document.querySelectorAll(".slide");
const numberOfSlides = slides.length;
var slideNumber = 0;
//image slider next button
nextBtn.addEventListener("click", () => {
slides.forEach((slide) => {
slide.classList.remove("active");
});
slideNumber++;
if (slideNumber > numberOfSlides - 1) {
slideNumber = 0;
}
slides[slideNumber].classList.add("active");
});
//image slider previous button
prevBtn.addEventListener("click", () => {
slides.forEach((slide) => {
slide.classList.remove("active");
});
slideNumber--;
if (slideNumber < 0) {
slideNumber = numberOfSlides - 1;
}
slides[slideNumber].classList.add("active");
});
//image slider autoplay
var playSlider;
var repeater = () => {
playSlider = setInterval(function() {
slides.forEach((slide) => {
slide.classList.remove("active");
});
slideNumber++;
if (slideNumber > numberOfSlides - 1) {
slideNumber = 0;
}
slides[slideNumber].classList.add("active");
}, 5000);
};
repeater();
//Get the button:
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() {
console.log('running')
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
Hope this helps.

These 2 windows.onscroll javascript codes don't work together

I am not a javascript expert. I have these two codes that don't work simultaneously. I don't know why and i ask you where could be the issue?
// This is the first part
//Get the button
var mybutton = document.getElementById("scrollToTop");
// 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 > 200 || document.documentElement.scrollTop > 200) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function toTopFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// When the user scrolls the page, execute myFunction
window.onscroll = function() {
myFunction()
};
// This is the second part
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 + "%";
}
Thanks to anyone
Every time you assign to window.onscroll it replaces the previous assignment.
If you want multiple event listeners, use addEventListener().
window.addEventListener("scroll", scrollFunction);
window.addEventListener("scroll", myFunction);
or call both functions in a single handler:
window.onscroll = function() {
scrollFunction();
myFunction();
};

Convert A Javascript Button Function To An Onload Function

I have a nicely working 'scrolltop' script that works fine throughout my site.
However, it is a 'button' function script.
In some cases, I need to execute this script from being a button function to an 'onload' function.
I'm not verse enough to be able to convert the script. If anyone can advise me on how to do that, it would be greatly appreciated.
Here is the script (button function):
<button onclick="topFunction()" id="myBtn"><span class="BtnText">Page Top<span></button>
<script>
window.onscroll = function() {scrollFunction()}; function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {document.getElementById("myBtn").style.display = "block";}
else {document.getElementById("myBtn").style.display = "none";}}
function topFunction() {document.body.scrollTop = 0; document.documentElement.scrollTop = 0;}
</script>
I'm not entirely sure if you meant to execute the function topFunction() when the page loads.
But, if that's the case:
<script>
window.onload = function() {
topFunction();
}
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
}
else {
document.getElementById("myBtn").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>

Javascript Scrolltop for fixed menu position

I want to stick my menu bar after scrolling few pixels in javascript but it is not working as it should. Here is my script.
JavaScript Code:
window.onscroll = function() {stick()};
function stick() {
if (document.body.scrollTop || document.documentElement.scrollTop > 150) {
document.getElementById("test").style.position = "fixed";
document.getElementById("test").style.background = "blue";
} else {
document.getElementById("test").style.position = "initial";
}
}
Problem:
Whenever I scroll even one pixel my test id get fixed. I tried to change scrollTop value in if but nothing effective. Any attention will be appreciated.
Update:
Here is also error using ids.
<script>
document.getElementById("cntnr").onscroll = function() {stick()};
function stick() {
if (document.getElementById("cntnr").scrollTop > 119) {
document.getElementById("navdwn").style.position = "fixed";
} else {
document.getElementById("navdwn").style.position = "initial";
}
}
</script>
Verify your If condition, to fix the menu current document scrolled to 150px top
change:
window.onscroll = function() {stick()};
function stick() {
if (document.body.scrollTop > 150 ) {
document.getElementById("test").style.position = "fixed";
document.getElementById("test").style.background = "blue";
} else {
document.getElementById("test").style.position = "initial";
}
}
The value of document.body.scrollTop will be greater than 0 as soon as you start scrolling. The OR operator will not check for the second condition if the first condition is true.
Hence as soon as you start scrolling the first condition becomes true and then the test id gets fixed.
Change the condition to if (document.body.scrollTop > 150 ) {.... and it will work.
try this code, you need the parseInt() function of the javascript to make the
document.documentElement.scrollTop equal to integer
window.onscroll = function() {stick()};
var offset = document.documentElement.scrollTop
function stick() {
if (parseInt(offset) > 150) {
document.getElementById("test").style.position = "fixed";
document.getElementById("test").style.background = "blue";
} else {
document.getElementById("test").style.position = "initial";
}
}

How to do scrollTop and toggleClass with Javascript and not jQuery?

In jQuery you can use method toggleClass and scrollTop but I´m trying to figure out how to do this with javascript.
I have a fixed <header> menu that I´m resizing when you scroll the window. So I want to add class="small" to the header with the help of javascript.
I have figured out the jQuery code:
$(document).on("scroll", function () {
$("header").toggleClass("small", $(document).scrollTop() > 100);
});
But I want to write this in javascript.
Below is what I´ve tried with so far but I´m stuck, any help appriciated:
function toggleMenu() {
var body = document.getElementsByTagName(body);
if (body > 100) {
document.getElementsByTagName('header').classList.toggle('small');
}
}
The following code will track if the user scrolls, and if they are 100px down the page, add the class small to all <header> tags.
window.onscroll = function() {
var el = document.getElementsByTagName('header');
var className = 'small';
for (var i=0; i<el.length; i++) {
if (el[i].classList) {
if (window.scrollY > 100)
el[i].classList.add(className);
else
el[i].classList.remove(className);
} else {
// IE Fix
if (window.scrollY > 100)
el[i].className += className;
else
el[i].className = str.replace(new RegExp("\\b"+className+"\\b","gi"),"");
}
}
}
Here's an example jsfiddle
If on the other hand you only have one <header> tag, you could add an id to it like so <header id='header'>, and run the following code. It will me a bit faster, but honestly you won't notice either way.
window.onscroll = function() {
var className = 'small';
var el = document.getElementById('header');
if (el.classList) {
if (window.scrollY > 100)
el.classList.add(className);
else
el.classList.remove(className);
} else {
// IE Fix
if (window.scrollY > 100)
el.className += className;
else
el.className = str.replace(new RegExp("\\b"+className+"\\b","gi"),"");
}
}
Here's an example jsfiddle
You did not mention browser compatibility so I'll assume it's IE8+
function handleScroll() {
var header = document.getElementsByTagName('header')[0],
var scrollTop = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop;
if(scrollTop > 100) {
if(header.classList) { // Modern browsers
header.classList.add = 'small';
}
else { // IE8-
header.className = 'blop small'; // Assuming your header already has a class 'blop'
}
}
else {
if(header.classList) { // Modern browsers
header.classList.remove = 'small';
}
else { // IE8-
header.className = 'blop'; // Assuming your header already has a class 'blop'
}
}
}
window.addEventListener('scroll', handleScroll, false); // Modern browsers
window.attachEvent('onscroll', handleScroll); // IE8-
window.onscroll = handleScroll; // If the other 2 are not available which is not likely to happen if you need to be compatible with IE8+
You might want to consider adding an id to your header since you can have more than one in your page, easier to select :
<header id="blop">[...]</header>
document.getElementById('blop');

Categories

Resources