Calling JavaScript On Click Before Landing Page URL Evaluates?
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,
Answer
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM