onclick return two functions (Tracking) - javascript

I'm trying to trigger two functions on the onclick event. They are used for tracking link from website. One is for GoogletagManager, the other one is for AdForm tracking.
I get error that the function is not defined. Any solutions to make this work?
Link
<script type="text/javascript">
function myFunction(){
secondone();
firstone();
}
function firstone() {
return console.log('first');
return gtag_report_conversion1('http://www.example.com');
}
function secondone() {
return console.log('second');
return window.adf&&adf.ClickTrack ( this,{123456},'Page Name',{});
}
</script>
<script>
function gtag_report_conversion1(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-465465465465465',
'event_callback': callback
});
return false;
}
</script>
<script type="text/javascript">
window._adftrack = Array.isArray(window._adftrack) ? window._adftrack : (window._adftrack ? [window._adftrack] : []);
window._adftrack.push({
pm: 123456,
divider: encodeURIComponent('|'),
pagename: encodeURIComponent('Page Name')
});
(function () { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://track.adform.net/serving/scripts/trackpoint/async/'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })();
</script>

After reading your edit - try moving all of the functions to the same <script></script> tag :)

Related

add exception on onbeforeunload

I have this code on my sites:
<script type="text/javascript">
var popit = true;
window.onbeforeunload = function() {
if(popit == true) {
popit = false;
setTimeout(function(){
window.open("/out.php", "_blank");
window.location.href = "/out.php";
}, 0);
return "Do you really wanna exit this website?";
}
popit= true;
}
function noPop() {
popit = false;
}
(function(w,l,d){var cloc=l.pathname+l.search;history.replaceState(null,d.title,l.pathname+"#!/back");history.pushState(null,d.title,l.pathname);w.addEventListener("popstate",function(){if(l.hash==="#!/back"){noPop();history.replaceState(null,d.title,l.pathname);setTimeout(function(){l.replace("/out.php");},0);}},false);}(window,location,document));
</script>
But I have also an popunder code that triggers my onbeforeunload:
<script src="/js/p.js" data-endpoint-uuid="07c9a1e6-76be-45cb-9788-7a3e4e42b69b" data-subid="default" data-mode="popup" defer></script>
How I can add an exception for that pop script?
thanks

How to unbind document keypress event with anonymous function

This is page's code.
I can't modify this.
var Example = {};
Example.create = function() {
var obj = new Example.object();
return obj;
}
Example.object = function(){
this.initialize = initialize;
function initialize() {
window.addEventListener('load', activate);
}
function activate() {
document.addEventListener('keypress', keyPressed);
}
function keyPressed(e) {
alert("Hello!");
}
};
Example.defaultObject = Example.create();
Example.defaultObject.initialize();
I have tried many things...
document.onkeypress = null;
document.keypress = null;
document.removeEventListener('keypress');
$(document).unbind('keypress');
$(document).off("keypress");
$("*").unbind('keypress');
$(document).bind('keypress', function(e) { e.stopPropagation(); });
but all failed.
How can I unbind event of document keypress?
You have to pass the listener to remove it: (a variable pointing the function aka the function name)
document.removeEventListener('keypress', keyPressed);
https://developer.mozilla.org/de/docs/Web/API/EventTarget/removeEventListener
You will have to save it somewhere to remove it later
Root cause of the issue is removeEventListener method. This method expect second parameter which is listener method
document.removeEventListener('keypress', Example.defaultObject.keyPressed);
Here you go for Solution on your problem.
var Example = {};
Example.create = function() {
var obj = new Example.object();
return obj;
}
Example.object = function(){
this.initialize = initialize;
function initialize() {
window.addEventListener('load', activate);
document.getElementById('disable').addEventListener('click', deActivate);
}
function activate() {
document.addEventListener('keypress', keyPressed);
}
function deActivate() {
document.removeEventListener('keypress', keyPressed);
document.querySelector('h1').innerHTML = 'Page Key Press Listener Removed';
}
function keyPressed(e) {
alert("Hello!");
}
};
Example.defaultObject = Example.create();
Example.defaultObject.initialize();
<body>
<h1>Page has Key Press Listener</h1>
<input id="disable" type="button" value="deactivate">
</body>

A script is executed/not executed due to when jQuery is loaded - Why?

This is a problem I have. Try this code:
if (typeof jQuery == 'undefined') {
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0];
done = false;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
};
};
head.appendChild(script);
};
getScript('http://code.jquery.com/jquery-1.11.2.min.js', function () {
if (typeof jQuery !== 'undefined') {
jQuery(document).ready(function ($) {
MyFunction($);
});
}
});
} else {
jQuery(document).ready(function ($) {
MyFunction($);
});
}
function MyFunction($) {
$.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?", function (d) {
}).done(function(d) {
JsonToHtml(d);
});
}
function JsonToHtml(html) {
var items = [];
$.each(html, function (key, val) {
items.push(val);
});
$('body').prepend(items.join(''));
}
you will notice that my code check if jQuery is loaded. If not, it loads a version from external source; than retrieve a JSON, parse it and "execute it".
As you can see, the script loaded inside the body it is not loaded at all (this is my problem).
Now, try to choose a version/library of jQuery in the fiddle (1.8.3 is ok) and press play: you will see the script/button render as well: the script is executed!!!
Why loading jQuery first (here) render the script, and load jQuery later won't execute the script? Can you help me?
I think your best bet is to force onload event to be refired if it is already fired because as you are loading jQuery (if undefined), this event is already fired. This is a workaround:
function JsonToHtml(html) {
var items = [];
$.each(html, function (key, val) {
items.push(val);
});
$('body').prepend(items.join(''));
if (document.readyState === 'complete') { // check if document is complete
var evt = document.createEvent('Event');
evt.initEvent('load', false, false);
window.dispatchEvent(evt); // then redispatch onload event
}
}
-DEMO-
I think the problem is the scope. The functions MyFunction() and JsonToHtml() are out of the scope. (Remember you are working with async functions like getJSON) Maybe my explanation are wrong, but the code works. :P
With this code you have no problem.
function _test(){}
_test.prototype = {
hasjQuery: function(){
if(typeof window.jQuery !='undefined' && !_test.prototype.otherLibrary() ) {
return true;
}else{
return false;
}
},
otherLibrary: function(){
if (typeof document.$ == 'function') {
return true;
}else{
return false;
}
},
inyectjQuery: function(url, success){
var script = document.createElement('script');
script.src = url;
script.id = "delete";
done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null
}
};
document.getElementsByTagName('head')[0].appendChild(script)
},
myFunction: function(){
urljQuery = 'http://code.jquery.com/jquery-latest.min.js';
if(_test.prototype.hasjQuery()){
jQuery.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?",
function (d) {
_test.prototype.JsonToHtml(d);
}).done(function() {
console.log("Success getJSON action");
});
}else{
_test.prototype.inyectjQuery(urljQuery, function(){
if (typeof window.jQuery == 'undefined') {
console.log("unable to load jQuery");
}else{
jQuery.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?",
function (d) {
_test.prototype.JsonToHtml(d);
}).done(function() {
console.log("Success getJSON action");
});
}
});
}
},
JsonToHtml: function(html){
var items = [];
jQuery.each(html, function (key, val) {
items.push(val);
});
jQuery('body').prepend(items.join(''));
}
}
test = new _test();
test.myFunction();

Every function in seperated js files but included only if used

Hey all im trying something (because im boring) every function as js files can be used but if only needed file will bi apended. so i have write something like this. some parts from this site.
library.js:
var jsfiles = new Array(
"jsLibrary/try.js",
"jsLibrary/try2.js"
);
var loadedJsFiles = [];
function loadFile(filepath,callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = filepath;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
function loadalljs(callback,jsnum){
if(!jsnum){jsnum = 0;}
if(jsnum<jsfiles.length){
if(!isArrayNode(jsfiles[jsnum],loadedJsFiles)){
loadedJsFiles.push(jsfiles[jsnum]);
loadFile(jsfiles[jsnum],function(){
loadalljs(callback,jsnum+1);
});
}else{
loadalljs(callback,jsnum+1);
}
}else if(jsnum==jsfiles.length){
callback();
}
}
function isArrayNode(str, arr) {
for (var i = 0; i < arr.length; i++) {
if (str == arr[i]) {
return true;
}
}
return false;
}
function lb(){
this.scripts = function(callback,includePageJs){
loadalljs(function(){
if(includePageJs){
loadFile(includePageJs,function(){
callback();
})
}else{
callback();
}
});
};
this.a = 5;
}
var library = new lb;
try.js:
function tryfunction(){
alert("try");
}
try2.js:
function try2(){
alert("try2");
}
mypage.js:
function mypagefunction(){
alert("mypagejs");
}
and im using it like this:
<script type="text/javascript" src="jsLibrary/library.js"></script>
<script>
library.scripts(function(){
tryfunction();
try2();
mypagefunction();
},"jsLibrary/mypagejs.js");
library.scripts(function(){
alert(library.a)
});
</script>
is there any way to do this with easy way? thanks for any idea or help. (Not in jquery please)
Use Requirejs
<script>
requirejs.config({
paths: {
'try1': '../path_to_your_try.js',
'try2': '../path_to_your_try2.js',
'mypage': '../path_to_your_mypage.js',
}
});
require([
'try1', 'try2', 'mypage'
], function(Try1, Try2, MyPage){
// Try1 refer to try1 file
// Try2 refer to try2 file
// MyPage refer to mypage file
});
</script>

How can I call a .js file in onclick event

I did like:
onclick="document.write('document.write(-------)');"
function importJavascript(src) {
var tag = document.createElement('SCRIPT');
tag.src = src;
document.getElementsByTagName('HEAD')[0].appendChild(tag);
}
Hope it helps
Click Here
<script>function getJs(src, callback) {
if (src && typeof src === "string") {
var el = document.createElement("script");
el.type = "text/javascript";
el.src = src;
document.head.appendChild(el);
el.onload = function(e) {
(callback && callback instanceof Function) ? callback(e) : void(0);
}
}
}
<script>
<div onclick='getJs("location_to_the_js_file.js")'></div>
what about using jQuery.getScript(), if you are using jQuery in your application already

Categories

Resources