Javascript Functions

0

Well, my code is working, but it's messy, if I try to organize it into functions it stops working:

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...
});

This does not 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
 }
});
    
asked by anonymous 03.04.2017 / 15:17

2 answers

6

Some problems with the code:

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

If you are going to even use declared functions, you should leave them out of the event you are adding ( addEventListener ).

2) One should be careful is for the scope of the variable. In its example, navbar is not available within the scope of mudaNav()

    
03.04.2017 / 15:23
2
___ erkimt ___ Javascript Functions ______ qstntxt ___

Well, my code is working, but it's messy, if I try to organize it into functions it stops working:

How it works:

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
}

This does not work:

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
}
    
______ azszpr194700 ___

Some problems with the code:

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

If you are going to even use declared functions, you should leave them out of the event you are adding ( %code% ).

2) One should be careful is for the scope of the variable. In its example, %code% is not available within the scope of %code%

    
______ ___ azszpr194704

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

%pre%     
___
03.04.2017 / 15:28