1
// 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' );
4
  • check the image tag must have id body22-popup Commented Jul 27, 2017 at 18:07
  • 1
    after your line with var img = could you add console.log(img.length) and tell the output in the console window Commented Jul 27, 2017 at 18:07
  • Do a null check for img before executing the code? Commented Jul 27, 2017 at 18:08
  • @taplr, please explain in detail as I am a Novice. Commented Jul 27, 2017 at 18:10

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

thanks sir, Let me try this. i will upload you soon.
my. upload me where..? :) -- it will work for you, the check for img first will not assign the click handler on pages when it doesn't exist, meaning your error goes away.
where I am testing and building wp theme.
this is how the console looks like now → screencast.com/t/3Of4GZeOFC (I can share the live link if troubleshooting like this is an issue)
No! you are checking for img before you even assign it, you assign it inside the if condition, that's not going to work.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.