My javascript function not working, greyed out - javascript

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.

Related

Adding class to element after scroll

So I'm working on showing/hiding a nav element based on scrolling behavior. Once the user scrolls and scrolls past the nav element, I add a class to make it sticky but keep it out of view. Then once the user stops scrolling I add another class to the transition the element into view. Once the user scrolls again that class needs to be removed again and the nav disappears again.
This is the JS
let mobile_toolbar = document.querySelector(".mobile-toolbar");
let mobile_toolbar_top = (mobile_toolbar.offsetTop) + 50;
let scrollpos = window.scrollY;
let timer = null;
window.addEventListener(
"scroll",
function () {
scrollpos = window.scrollY;
console.log(timer)
if (timer !== null) {
if (scrollpos > mobile_toolbar_top) {
mobile_toolbar.classList.add("mobile-toolbar__hidden");
mobile_toolbar.classList.remove("mobile-toolbar--fixed");
clearTimeout(timer);
} else {
mobile_toolbar.classList.remove("mobile-toolbar__hidden");
mobile_toolbar.classList.remove("mobile-toolbar--fixed");
clearTimeout(timer);
}
}
if (scrollpos > mobile_toolbar_top) {
timer = setTimeout(function () {
mobile_toolbar.classList.add("mobile-toolbar--fixed");
}, 400);
}
},
false
);
As you can see I'm setting a timer to detect when the user stops scrolling and also check the scroll position to determine whether the add the fixed class or not. However, this isn't quite working as I'd like as the nav once slides down as soon as I scroll past itself and then disappears again as the timer is already not null at this point. Can anyone tell me what's wrong with my cod or if there's a better way to detect when the user has stopped scrolling? Vanilla JS only please as I'm trying not to use jQuery
you can refer a below code (it's tell you when user stop scrolling)
<html>
<body onscroll="bodyScroll();">
<script language="javascript">
var scrollTimer = -1;
function bodyScroll() {
document.body.style.backgroundColor = "white";
if (scrollTimer != -1)
clearTimeout(scrollTimer);
scrollTimer = window.setTimeout("scrollFinished()", 500);
}
function scrollFinished() {
document.body.style.backgroundColor = "red";
}
</script>
<div style="height:2000px;">
Scroll the page down. The page will turn red when the scrolling has finished.
</div>
</body>
</html>
Check out this example:
https://codepen.io/len0xx/pen/JjadOgR
const toolbar = document.querySelector('.mobile-toolbar')
const mobileToolbarTop = (toolbar.offsetTop) + 50
let previousScroll = 0
let previousTimeout = 0
window.addEventListener('scroll', () => {
const currentScroll = window.scrollY
if (currentScroll > mobileToolbarTop) {
if (currentScroll > previousScroll) {
toolbar.classList.add('mobile-toolbar__hidden')
toolbar.classList.remove('mobile-toolbar--fixed')
}
else {
toolbar.classList.remove('mobile-toolbar__hidden')
toolbar.classList.add('mobile-toolbar--fixed')
}
}
if (previousTimeout) {
clearTimeout(previousTimeout)
}
previousTimeout = setTimeout(() => {
const newScroll = window.scrollY
if (newScroll <= currentScroll) {
toolbar.classList.remove('mobile-toolbar__hidden')
toolbar.classList.add('mobile-toolbar--fixed')
}
}, 300)
previousScroll = currentScroll
})

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();
};

Scroll page effect javascript

I have a button that if is pressed, the page scroll to top.
But i want the scroll id made by an animation, can you help me? PS. i prefer javascript than jquery. Thanks.
window.onscroll = function() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
};
window.onload = function() {
document.getElementById("myBtn").onclick = function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
}
This is my current javascript.
Try this:
window.onload = function() {
document.getElementById("myBtn").onclick = function() {
window.scroll({
top: 0,
behavior: "smooth"
});
}
}

More than one function on scroll?

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
}

Why does my "back to top" button only work when I am at the bottom of the page?

// 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) {
document.getElementById("Button").style.textAlign = "center".display =
"block";
} else {
document.getElementById("Button").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;
}

Categories

Resources