Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

javascript - Onclick with window.onload function

I've no idea if this is the right way to do what I'm trying to do (I have 0 experience with jQuery/Javascript):

window.onload = function () {
     var Btn = document.getElementById('fmm-payment-btn');
     Btn.onclick = function () {
         gtag_report_conversion();
     }
}

The gtag_report_conversion() looks like this:

function gtag_report_conversion(url) {
  var callback = function () {
    if (typeof(url) != 'undefined') {
      window.location = url;
    }
  };
  gtag('event', 'conversion', {
      'send_to': 'AW-URLHERE',
      'transaction_id': '',
      'event_callback': callback
  });
  return false;
}

Basically, I'd like to make sure that the function gtag_report_conversion() is executed when users click on fmm-payment-btn (to track conversions in Google Ads).

I tried this in a slightly different way using document.getElementById("fmm-payment-btn").onclick = function() but I kept getting an error, Uncaught TypeError: Cannot set property 'onclick' of null. I understand the method above should work better, but having no experience I cannot tell.

Would appreciate any feedback. :)

question from:https://stackoverflow.com/questions/65871500/onclick-with-window-onload-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

window.onload doesn't mean that the DOM is loaded.

If you want to be sure that the button is rendered you should use

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
    document.getElementById("fmm-payment-btn").onclick = function(){}
    // Or
    document.getElementById("fmm-payment-btn").addEventlistener('click', function(){})
    // Or even cleaner
    document.getElementById("fmm-payment-btn").addEventlistener('click', gtag_report_conversion)
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...