Courtney Whiting
asked on
Help with - Cannot set property 'onclick' of null
I am creating a pop-up when a button on a site is clicked and everything works fine until it's time to close the pop-up. I have created a close button with JS but now when trying to apply it, I get `Cannot set property 'onclick' of null`. Any idea's why my `#btn2` is considered a null value? Here's the code:
var vaderPopup = function() {
//Create elements
var cover = document.createElement('img');
var closeBtn = document.createElement('div');
//Assign id's to elements
cover.id = "cover";
closeBtn.id = "closeBtn";
//Add image src to popup
cover.src = "images/click-vader.jpg";
cover.style.display = 'block';
cover.style.margin = 'auto';
cover.style.zIndex = 100;
cover.style.width = '100%';
cover.style.height = '100%';
cover.style.position = 'absolute';
cover.style.top = '180px';
cover.style.left = 0;
cover.style.opacity = '.9';
//Add CSS to closeBtn
closeBtn.style.backgroundColor = '#A7A7AC';
closeBtn.style.border = '1px solid #CCC';
closeBtn.style.textAlign = 'center';
closeBtn.style.position = 'absolute';
closeBtn.style.top = '100%';
closeBtn.style.right = '50%';
closeBtn.style.bottom = '50%';
closeBtn.style.left = '43%';
closeBtn.style.width = '200px';
closeBtn.style.height = '100px';
closeBtn.style.padding = '0 8px 0 8px';
closeBtn.style.opacity = '.8';
closeBtn.style.zIndex = '200';
//Add content to closeBtn
closeBtn.innerHTML = "<h3><strong>You have chosen wisely...</strong></h3>";
closeBtn.innerHTML += "<button id='btn2'>Return</button>";
//Add cover and closeBtn to page
document.querySelector('#vader').onclick = function() {
document.querySelector('body').appendChild(cover);
document.querySelector('body').appendChild(closeBtn);
}
var closePopup = function() {
cover.style.display = 'none';
closeBtn.style.display = 'none';
}
document.querySelector('#btn2').onclick = closePopup;
}();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You're welcome. Thanks for the points.
ASKER
Open in new window
and:Open in new window
to re-add the pop-up, kinda what you were suggesting in your second idea.
Thanks!