Home > other >  How to use JS codes which are specific to some pages from a single JS file containing JS codes for a
How to use JS codes which are specific to some pages from a single JS file containing JS codes for a

Time:10-15

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related