Home > Blockchain >  Hidden Javascript Button on larger screen
Hidden Javascript Button on larger screen

Time:01-17

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>

CodePudding user response:

Use window.innerWidth property.

Something like,

window.onscroll = function() {
  if (window.innerWidth <= 600) {
    scrollFunction();
  }
};

Sample: https://jsfiddle.net/codeandcloud/sezk0j74/

CodePudding user response:

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.

  •  Tags:  
  • Related