0

I am trying to add an event listener to an element, but no matter what I try, it won't work. Here is what I have so far (this is in the html web templates page):

window.addEventListener('load',function(){
        document.getElementById('authnetcim-submit').addEventListener("click", function(){
            alert('Alert Message');
        });
    });

Everyone keeps saying that the listener needs to be wrapped in window.addEventListener('load'), as you need to wait for the page to load before you can add the listeners, but that still won't work for me either. There are no errors and nothing logs to the console. The Id is correct and it's the only id of that name used on the page.

Any help is appreciated.

0

You only need the domReady! dependency. If you're in Magento 2, you should be using require JS anyways. Here's the best of both worlds.

define([
    'domReady!'
], function () {
    'use strict';

    //do your thing here
});

OR require instead of define. Depends on how you're calling the functionality.

require([
    'domReady!'
], function () {
    'use strict';

    //do your thing here
});
  • I tried this out, but it still wasn't working. I'm getting the error "Cannot read property 'addEventListener' of null." I added in a .phtml file require([ 'domReady!' ], function () { alert('phtml loaded'); var getElementById = document.getElementById("billing-address-same-as-shipping-authnetcim"); document.getElementById('authnetcim-submit').addEventListener("click", function(){ alert('Alert Message'); }); }); – Eric Brown Mar 27 at 22:48
  • console.log(window) to see if window is null. If it is you have a different issue – Shawn Abramson Mar 27 at 23:12
  • It's not null, it prints Window object. – Eric Brown Mar 27 at 23:30
  • how does the authnetcim-submit element get output to the page? – Shawn Abramson Mar 27 at 23:32
  • I believe it's through Knockout. – Eric Brown Mar 28 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.