OnScroll function in JS

Asked

Viewed 58 times

0

I’m putting this code in a separate script from HTML, but it doesn’t work 100%. When I create the tag <scrip></script> within the HTML it works, someone can explain me the reason?

filing cabinet .js

scrollFunction = function () {
var navbar = document.getElementById("myNavbar");
var sticky = navbar.offsetTop;

var x = window.matchMedia("(max-width: 600px)")

   if (x.matches) { 
    
        if (window.pageYOffset >= sticky) {
            navbar.classList.add("sticky")
        } else if (window.pageYOffset < sticky){
            navbar.classList.remove("sticky");
        }  
    } else {
     
        if (window.pageYOffset > sticky) {
            navbar.classList.add("sticky")
        } else if (window.pageYOffset < sticky) {
            navbar.classList.remove("sticky");
        }  
    }
};

Same goes for that code underneath mine onClick.

tstar = function() {
var sticky;
  var x = document.getElementById("myNavbar");
  if (x.className === "navbar sticky") {
    x.className += " responsive";
  }else if (x.className === "navbar sticky responsive") {
    x.className = "navbar sticky";
  }
  else if (x.className === "navbar"){
    x.className += " responsive";
  } 
  else {
    x.className = "navbar";
  }
};

  • You’re indexing this . JS inside the <head> of your document? Or it is placing there at the end of the document after all the code, but just before the closing tag of the </body>?

  • Yes, I am! He takes other scripts, but he’s not reading these two that I mentioned :( <script src="http://agropecuariasertaneja.com.br/assets/js/script.js"></script>

  • 1

    Did you write your Script tag exactly like this? If it was missing http://or https:// in the path of your file... Ideally the . JS always come at the end of the document, just before the body closes

  • the problem is not there, as said have other scripts working! Sorry, the stack removed http rsrs but it is correct in html!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.