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.
Related
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>
I'm using this code to make my sticky navbar disappear on scroll down and re-appear on scroll up. However this code is pretty precise resulting sometimes in starting one of both animations without actually scrolling.
What I'm trying to achieve is that a user should scroll 20px down before the if statement runs. Same if they would scroll up again...
https://jsfiddle.net/as1tpbjw/2/
const body = document.querySelector("#navbar");;
let lastScroll = 0;
window.addEventListener("scroll", () => {
const currentScroll = window.pageYOffset;
if (currentScroll <= 0) {
body.classList.remove("scroll-up");
return;
}
if (currentScroll > lastScroll && !body.classList.contains("scroll-down")) {
body.classList.remove("scroll-up");
body.classList.add("scroll-down");
} else if (
currentScroll < lastScroll &&
body.classList.contains("scroll-down")
) {
body.classList.remove("scroll-down");
body.classList.add("scroll-up");
}
lastScroll = currentScroll;
});
As far as I can see, in my relatively old version of Firefox, it works well.
I added if (Math.abs(currentScroll - lastScroll) < 20) { return; } and this adds a 20px delay either way.
Also, that scroll-up class doesn't seem to be doing anything in the fiddle.
Update:
If you want an animation, you can replace the CSS for .scroll-down and add a transition to #navbar:
#navbar.scroll-down {
height: 0;
}
#navbar {
/* … */
transition: height .5s;
}
Not only does scroll-up do nothing, but the following code even breaks (doesn't show the navbar) when you scroll to the top:
if (currentScroll <= 0) {
body.classList.remove("scroll-up");
return;
}
You may want to remove it.
const body = document.querySelector("#navbar");
let lastScroll = 0;
window.addEventListener("scroll", () => {
const currentScroll = window.pageYOffset;
if (Math.abs(currentScroll - lastScroll) < 20) {
return;
}
if (currentScroll > lastScroll) {
body.classList.add("scroll-down");
} else {
body.classList.remove("scroll-down");
}
lastScroll = currentScroll;
});
body {
margin: 0;
min-height: 200vh;
}
#navbar.scroll-down {
height: 0;
}
#navbar {
height: 50px;
background: red;
position: sticky;
top: 0;
left: 0;
transition: height .5s;
}
<body>
<div id="navbar">
</div>
</body>
I'm working on a website of mine, that has a header and a filter section on the top of the page. What I'm trying to do is to make the filter section stick to the top of the page when the page is scrolled down, but only if the device/browser is under a specific width, in this case 1000px.
My problem is that i could only figure out how to update the browsers width after it is resized and then refreshed.
document.body.onscroll = scroll;
var navbar = document.getElementById("navbar");
var bodyTop = navbar.offsetTop;
var browserWidth = window.innerWidth;
navbar.innerHTML = browserWidth + " (Current browser width)"
function scroll() {
if (browserWidth < 1000) {
if (document.documentElement.scrollTop > 65) {
navbar.style.position = "fixed";
navbar.style.top = "0";
}
if (document.documentElement.scrollTop < 65) {
navbar.style.position = "relative";
navbar.style.top = "0";
}
}
};
html,
body {
margin: 0;
height: 2000px;
}
#header {
width: 100%;
background-color: darkred;
height: 65px;
position: relative;
}
#navbar {
width: 100%;
height: 85px;
position: relative;
background-color: grey;
}
<div id="header"></div>
<div id="navbar"></div>
You can use the onresize event to update the value of browserWidth whenever the window is resized:
document.body.onscroll = scroll;
var navbar = document.getElementById("navbar");
var bodyTop = navbar.offsetTop;
var browserWidth = window.innerWidth;
navbar.innerHTML = browserWidth + " (Current browser width)"
window.onresize = function() {
browserWidth = window.innerWidth; //update value of browserWidth
}
function scroll() {
if (browserWidth < 1000) {
if (document.documentElement.scrollTop > 65) {
navbar.style.position = "fixed";
navbar.style.top = "0";
}
if (document.documentElement.scrollTop < 65) {
navbar.style.position = "relative";
navbar.style.top = "0";
}
}
};
I have an image on a page that have a absolute position to be in the center of the page when it loads. When the user scroll down the page and the image reach a position of 20% from the top of the screen, I want to change the position of that image to fixed so it always stays on the screen at 20% from the top of the screen.
I guess that I will have to do something like this :
$(function () {
$(window).scroll(function () {
var aheight = $(window).height() / 2;
if ($(this).scrollTop() >= aheight) {
$("#image").css("position", "fixed");
}
else {
$("#image").css("position", "absolute");
}
});
});
This line is where I should put the 20% from top but I don't know how :
var aheight = $(window).height() / 2;
EDITED CODE (still not working but I forgot to post the var in my original post and the scroll height was set at 50% instead of 20%):
var t = $("#logo").offset().top;
$(function () {
$(window).scroll(function () {
var aheight = $(window).height() / 5;
if ($(this).scrollTop() >= aheight) {
$("#logo").css("position", "fixed");
}
else {
$("#logo").css("position", "absolute");
}
});
});
English is not my first language so I drew what I want to do in case my explanation was not clear :
Image of what I'm looking for
EDIT 2 (ANSWER) :
Stackoverflow won't let me answer my question because I don't have enough reputation so here is the working code I came with :
$(document).scroll(function(){
var bheight = $(window).height();
var percent = 0.3;
var hpercent = bheight * percent;
if($(this).scrollTop() > hpercent)
{
$('#logo').css({"position":"fixed","top":"20%"});
}else{
$('#logo').css({"position":"absolute","top":"50%"});
}
});
Check this fiddle.
http://jsfiddle.net/livibetter/HV9HM/
Javascript:
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function () {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
CSS:
#sticky {
padding: 0.5ex;
width: 600px;
background-color: #333;
color: #fff;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
border-radius: 0 0 0.5em 0.5em;
}
body {
margin: 1em;
}
p {
margin: 1em auto;
}
Alternatively, you can take a look at jquery-waypoints plugin. The use is as easy as:
$('#your-div').waypoint(function() {
console.log('25% from the top');
// logic when you are 25% from the top...
}, { offset: '25%' });
I'm having a hard time finding a Javascript piece of code to dynamically show the Back to Top button when the user has scrolled, lets say, more than 1000 pixels. All examples use jQuery, and I can't use jQuery. Any help will be very appreciated.
Set the CSS when pageOffset is a certain point (in a window.onscroll event):
window.onscroll = function()
{
if(pageOffset >= 1000)
{
document.getElementById('backToTopID').style.visibility="visible"
}
};
something more full would be:
window.onscroll = function()
{
if(pageOffset >= 1000)
{
document.getElementById('backToTopID').style.visibility="visible"
}else
{
document.getElementById('backToTop').style.visibility="hidden";
}
};
DEMO
JavaScript using Window.onscroll
var appended = false, bookmark = document.createElement("div");
bookmark.id = "arrowUp";
bookmark.innerHTML = "<a href=\"#\" title=\"Top of the page.\">↑<\/a>";
onscroll = function() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 500) {
if (!appended) {
document.body.appendChild(bookmark);
appended = true;
}
} else {
if (appended) {
document.body.removeChild(bookmark);
appended = false;
}
}
};
source
https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll
demo link
http://jsfiddle.net/MA4dC/
This is how I do it. To show back to top button when user scrolls more than 150 pixels down from top of document.
//how to show back to top button when user scrolls more than 150 pixels down from top of document.
var toTopButton = document.querySelector("a");
toTopButton.style.display = "none";//by default should be hidden
document.querySelector('body').onscroll = function(){//whenever they scroll
if (window.scrollY > 150)//if scroll is 150px from top
toTopButton.style.display = "block";//if they scroll down, show
else
toTopButton.style.display = "none";//if they scroll up, hide
};
html {scroll-behavior: smooth;}
a {
background-color: #f00;
position: fixed;
bottom: 10px;
right: 10px;
}
<html>
back to top
<body id="top">
text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>
</body>
<html>
OR to show back to top button when user scrolls more than 150 pixels up from bottom of document.
//how to show back to top button when user scrolls more than 150 pixels up from bottom of document.
var toTopButton = document.querySelector("a");
toTopButton.style.display = "none";
document.querySelector('body').onscroll = function(){
if (window.innerHeight + 150 < document.body.offsetHeight)//if document long enough
if (window.scrollY + window.innerHeight > document.body.offsetHeight - 150)//if scroll is 150px from bottom (if 'bottom of what we are looking at' is > than 'bottom of document - 150px earlier)
toTopButton.style.display = "block";
else
toTopButton.style.display = "none";
};
html {scroll-behavior: smooth;}
a {
background-color: #f00;
position: fixed;
bottom: 10px;
right: 10px;
}
<html>
back to top
<body id="top">
text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>
</body>
<html>
Simple but working.
CSS:
#scrollToTop { visibility: hidden; }
JavaScript:
// Show/Hide the button
window.onscroll = function() {
var pageOffset = document.documentElement.scrollTop || document.body.scrollTop,
btn = document.getElementById('scrollToTop');
if (btn) btn.style.visibility = pageOffset > 450 ? 'visible' : 'hidden';
};