Calling JavaScript On Click Before Landing Page URL Evaluates?

- 1 answer

Ad

I want to call a JavaScript file on click. Once the file loads, I want to redirect the user to a landing page.

This is my code:

<script type="text/javascript">


    document.getElementsByTagName("body").onclick = function () {
        var js = document.createElement("script");
        js.type = "text/javascript";
        js.onload = function () {
            window.location.href = "https://google.com/";
        };
        js.src = "((JAVASCRIPT SOURCE))";
        document.body.appendChild(js);
     };
    </script>

The purpose of delaying the landing page until the script loads is because some browsers load the landing page before the script does and I need the script to be called for tracking purposes. It's just used to capture total "clicks", if you will.

Can you help me figure out why the above is not working? I try to invoke the script when the body is clicked on, and then once the script loads, use window.open to go to the landing page.

Thanks,

Ad

Answer

Ad

First of all document.getElementsByTagName() returns a HTMLCollection:

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name.

To access the first element, to be able to attach your event listener, you have to do this:

document.getElementsByTagName('body')[0].onclick = function () { ... }

And instead of document.getElementsByTagName('body')[0] you could just use this shorthand, which you already used further down:

document.body.onclick = function () { ... }

Also, if your script is placed in <head> you need to wrap it in onLoad or onDOMContentLoaded:

window.onload = function() {
  document.body.onclick = function() {
    var js = document.createElement("script");
    js.type = "text/javascript";
    js.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js";
    document.body.appendChild(js);
    js.onload = function() {
      window.location.href = "https://www.example.com";
    };
  };
}
CLICK ME

Ad
source: stackoverflow.com
Ad