Improve code logo menu javascript

0

How can I improve this code? In every scroll it does this check and places one on top of the other. It is functional, but I find it very heavy and with many requests. Any tips on how I can improve it?

function criaLogoPrincipal() {
  var logoMenuPrincipal = document.createElement("div");
  logoMenuPrincipal.classList.add("logo");
  logoMenuPrincipal.classList.add("col-xs-2");

  var imgMenu = document.createElement("img");
  imgMenu.src="img/logoBranco.png";
  imgMenu.classList.add("logoCor");

  logoMenuPrincipal.appendChild(imgMenu);

  return logoMenuPrincipal;
}   

function criaLogoSecundario() {
  var logoMenuBranco = document.createElement("div");
  logoMenuBranco.classList.add("logo");
  logoMenuBranco.classList.add("col-xs-2");
  var imgMenu = document.createElement("img");
  imgMenu.src="img/logo.png";
  imgMenu.classList.add("logoCor");
  logoMenuBranco.appendChild(imgMenu);

  return logoMenuBranco;
}

var paiLogo = document.querySelector(".second-logo-branco");
var logoMenuBranco = criaLogoSecundario();   
var logoMenuPrincipal = criaLogoPrincipal();   
paiLogo.appendChild(logoMenuPrincipal);

window.onscroll = function() {
  console.log(window.pageYOffset);

  if (window.pageYOffset > 42) {
    paiLogo.appendChild(logoMenuBranco);
  } else if (window.pageYOffset <= 42) {                
    paiLogo.appendChild(logoMenuBranco);
    paiLogo.appendChild(logoMenuPrincipal);
    paiLogo.removeChild(logoMenuBranco);            
  }

  /*console.log(window.pageYOffset);
    if (document.body.scrollTop < 10) {                      
      paiLogo.appendChild(logoMenuPrincipal);
    } else if(document.body.scrollTop >= 10) {                        
      paiLogo.appendChild(logoMenuBranco);
    }
  }*/             
}
    
asked by anonymous 22.08.2017 / 19:47

1 answer

0

One of the things I would do is just create a function and give it the image's address as a parameter:

function criarLogo(endImagem) {
  var logoMenuPrincipal = document.createElement("div");
  logoMenuPrincipal.classList.add("logo");
  logoMenuPrincipal.classList.add("col-xs-2");

  var imgMenu = document.createElement("img");
  imgMenu.src = endImagem;
  imgMenu.classList.add("logoCor");

  logoMenuPrincipal.appendChild(imgMenu);

  return logoMenuPrincipal;
}

var paiLogo = document.querySelector(".second-logo-branco");
var logoMenuBranco = criarLogo("img/logo.png");   
var logoMenuPrincipal = criarLogo("img/logoBranco.png");   
paiLogo.appendChild(logoMenuPrincipal);

window.onscroll = function() {
  console.log(window.pageYOffset);

  if (window.pageYOffset > 42) {
    paiLogo.appendChild(logoMenuBranco);
  } else if (window.pageYOffset <= 42) {                
    paiLogo.appendChild(logoMenuBranco);
    paiLogo.appendChild(logoMenuPrincipal);
    paiLogo.removeChild(logoMenuBranco);            
  }            
}
    
22.08.2017 / 20:04