1
votes
// Get the modal
    var modal = document.getElementById('bozy-mymodal');
    // Get the image and insert it inside the modal - use its "alt" text as a caption
    var img = document.getElementById('bozy22-popup');
    var modalImg = document.getElementById("image-01");
    var captionText = document.getElementById("caption");
    img.onclick = function(){
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    }

This code is there in my custom.js in my WordPress theme, and it handles the image Popup, but on the front page opr other pages when there is no such even to handle than other Jqueries or custom queries written in custom.js doesn't execute such as Popmenu etc. what is the solution?

Uncaught TypeError: Cannot set property '**onclick**' of null
    at custom.js:20
    at custom.js:44

That seems to be looking for an image called body22-popup, which doesn't exist on that page but does on the page where the slider works.

var img = document.getElementById('body22-popup');

a similar situation is here → i'm getting an Uncaught TypeError: Cannot set property 'onclick' of null?

Is there a way to execute that part of the code in custom.js where such image that could be popped up doesn't exist.

In Wordpress, the scripts are added like this →

wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
        wp_enqueue_script( 'custom-js' );
1
check the image tag must have id body22-popup - RAUSHAN KUMAR
after your line with var img = could you add console.log(img.length) and tell the output in the console window - Carsten Løvbo Andersen
Do a null check for img before executing the code? - Chang Liu
@taplr, please explain in detail as I am a Novice. - somethingnow

1 Answers

2
votes

So make sure that img is not null before you try to assign the handler:

...
var img = document.getElementById('bozy22-popup');
if ( img ) 
{
    img.onclick = function(){
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    }
}