Functions in Javascript

Asked

Viewed 44 times

0

Guys, my code is working, only it’s messy, if I try to organize in functions it stops working:

That’s how it works:

var navbar = document.getElementById('nav');
document.addEventListener("scroll", function() {
  var posicaoy = window.pageYOffset;
  console.log(posicaoy);
  navbar.style.backgroundColor = posicaoy == 0 ? "transparent" : "white";

  //outras coisas aqui...
});

So it doesn’t work:

var navbar = document.getElementById('nav');
document.addEventListener("scroll", function() {
  var posicaoy = window.pageYOffset;
  console.log(posicaoy);

 function mudaNav(){
  navbar.style.backgroundColor = posicaoy == 0 ? "transparent" : "white";
 }
 function mudabla1(){
  //Codigo aqui
 }

 function mudabla2(){
  //Codigo aqui
 }
});

2 answers

6

Some problems with the code:

1) You are declaring functions within a lambda (anonymous function).

If you’re actually going to use declared functions, you should leave them outside the event you’re adding (addEventListener).

2) Attention should be paid to the scope of the variable. In your example, navbar is not available within the scope of mudaNav()

  • Very good, I’ll check, I’m working with many global scopes, I need to adjust this.

  • if you’re using jQuery, try using custom plugins

  • I’m using pure js, I was getting too dependent on Jquery, but obg by tip.

2

You seem to be having a problem understanding scope and function arguments.

document.addEventListener("scroll", function() {
  mudaNav(window.pageYOffset);
});

function mudaNav(posY) { // precisa receber como argumento
  var navbar = document.getElementById('nav'); // é melhor ter no mesmo escopo
  navbar.style.backgroundColor = (posY == 0) ? "transparent" : "white";
}

function mudabla1(){
  //Codigo aqui
}

function mudabla2(){
  //Codigo aqui
}
  • 1

    As in C++ I should not declare the functions before calling them, or Javascript is already asynchronous by default?

  • Javascript is asynchronous by default and all variable and function statements will always be "moved" to the top script by the interpreter, making them available at the very beginning of the scope execution.

Browser other questions tagged

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