Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

333
Visualizações
How to use JS codes which are specific to some pages from a single JS file containing JS codes for all the pages?

On my website, I included all my JavaScript codes in a single file common.js. The problem which I am facing is some of my JS codes are specific to one page. So it shows an error on another page.

For example, I have a user icon having id 'user_icon' that is present on only one page, for that page, everything is working fine but for another page, it shows me the error "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at common.js:11". It means JS couldn't find that element on another page. So, how I can fix this problem? Any suggestion is highly appreciated.

Here's the code for the user icon

var user_icon = document.getElementById('user-icon');
var menu = document.getElementById('menu');
var x = -100;
user_icon.addEventListener('click', function () {
    if (x == -100) {
        x = 0
        menu.style.right = x;
        menu.style.opacity = 1;
    }
    else {
        x = -100
        menu.style.right = x + '%';
        menu.style.opacity = 0;
    }
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can add a trap for this. Thst should remove Uncaught TypeError error.

var user_icon = document.getElementById('user-icon');
var menu = document.getElementById('menu');
var x = -100;
if(user_icon && menu)
{
    user_icon.addEventListener('click', function () {
        if (x == -100) {
            x = 0
            menu.style.right = x;
            menu.style.opacity = 1;
        }
        else {
            x = -100
            menu.style.right = x + '%';
            menu.style.opacity = 0;
        }
    })
}
about 4 years ago · Juan Pablo Isaza Relatório

0

When you remove DOM content which is having event binded on it, you MUST remove those event before removing the content.

You can do so by triggering a bindEvent and unbindEvents :


window.onload = bindEvents

var menu = document.getElementById('menu');
var x = -100;

function bindEvents() {
  var user_icon = document.getElementById('user-icon');
  user_icon.addEventListener('click', myAction, true);
}

function unbindEvents() {
  var user_icon = document.getElementById('user-icon');
  user_icon.removeEventListener('click', myAction, true);
}

function myAction() {
    if (x == -100) {
        x = 0
        menu.style.right = x;
        menu.style.opacity = 1;
    }
    else {
        x = -100
        menu.style.right = x + '%';
        menu.style.opacity = 0;
    }
}

You are free to call bindEvents and unbindEvents at the appropriate time, but keep in mind that your element has to be in the DOM when those are called. Otherwise, you'll leave some zombie events on your page and that is a serious memory leak especially when building single page application.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda