简体   繁体   中英

Cannot get onclick event to work in WordPress

I realize that this question may have already been answered, but I just cannot get it work. Keep in mind that this works fine outside WordPress.

I am getting this error when page is loaded up: (index):54 Uncaught TypeError: Cannot read property 'addEventListener' of null at (index):54.

And I am getting this error when Privacy policy is clicked: (index):50 Uncaught TypeError: Cannot read property 'classList' of null at togglePopup ((index):50) at HTMLDivElement.onclick ((index):477)

HTML:

<div class="popup-backdrop"></div>
 <div class="popup" onclick="togglePopup()">Privacy policy.

<span class="popuptext" id="myPopup">
    Popup text to show up.
  </span>
</div>

JS:

const popup = document.getElementById("myPopup");
const backdrop = document.querySelector('.popup-backdrop');

function togglePopup () {
  popup.classList.toggle('show');
  backdrop.classList.toggle('popup-opened');
};

backdrop.addEventListener('click', closePopup);

function closePopup () {
  popup.classList.toggle('show');
  backdrop.classList.toggle('popup-opened');

};

I have included JavaScript in WordPress via functions.php file like this:

wp_enqueue_script( 'main-js-file', get_template_directory_uri() . '/js/main.js'); 

Also other JavaScript I have in there works.

Any help, please?

It seems like event listener is trying to bind before the relevant DOM object loads. One possible solution to this problem is to add your event listener once all objects are loaded. Try:

  document.onload()=function() {
   const popup = document.getElementById("myPopup");
   const backdrop = document.querySelector('.popup-backdrop');
   backdrop.addEventListener('click', closePopup);
  };

OR with jQuery

jQuery(document).ready(function(){
 const popup = document.getElementById("myPopup");
 const backdrop = document.querySelector('.popup-backdrop');
 backdrop.addEventListener('click', closePopup);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM