tiffsen
tiffsen

Reputation: 27

combine script with mediaquerie

i want this script https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_navbar_hide_scroll working only for a defined screensize. I tried out to combine it with following screensize-condition

if (document.documentElement.clientWidth < 600)

but i am still missing something to get it working.

<script>
if (document.documentElement.clientWidth < 600) {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 = "-50px";
  }
  prevScrollpos = currentScrollPos;
}}
</script>
<style>
body {
  margin: 0;
  background-color: #f1f1f1;
      }

#navbar {
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
  display:block;
  }

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 15px;
  }

#navbar a:hover {
  background-color: #ddd;
  color: black;
}
</style>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

<div id="navbar">
  </div>


<div>  
  <p>bla</p>
  <p>bla</p>
  <p>bla</p>
</div>

</body>
</html>

and what about a second wrapper inside the navbar? Its causing the function not to work anymore...

`<div id="navbar">
  <a href="#home">Home</a>
  <div id="second div-id"><a href="#home">Home</a>   </div>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>`

Upvotes: 0

Views: 97

Answers (1)

londongrammar
londongrammar

Reputation: 163

if you need a window width without scrollbars

if (window.innerWidth < 600) { // your code here }

with scrollbars

if (window.outerWidth < 600) { // your code here }

Here’s the working fiddle.

Please note: the navbar script only being executed when you load the page in browser window smaller than 600px. If you want it to be triggered not only on page load but also when scaling browser window up and down - you should use a resize event on window object.

And if you’re testing in fiddle browser - javascript running in the fiddle calculates the fiddle browser width, not the actual native browser width.

Upvotes: 1

Related Questions