How can I call a .js file in onclick event - javascript

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

Related

Append a generated script after a specific div

Have this code :
<script>
(function()
{
let relScript = document.createElement('script');
relScript.src="https://mountain.com/assets/js/sso.js";
relScript.type  = "text/javascript";
relScript.async  = true;
relScript.defer  = true;
$('.skip-page').append(relScript);
})();
</script>
The script is attached to body and not to this <div class="skip-page">;
My goal is to put this script after the div skip-page; Any ideas why is append to body ?
using load event
// not use JQuery
window.onload = function (){
let relScript = document.createElement('script');
relScript.src="https://mountain.com/assets/js/sso.js";
relScript.type = "text/javascript";
relScript.async = true;
relScript.defer = true;
$('.skip-page').append(relScript);
};
// Using JQuery
$(function(){
let relScript = document.createElement('script');
relScript.src="https://mountain.com/assets/js/sso.js";
relScript.type = "text/javascript";
relScript.async = true;
relScript.defer = true;
$('.skip-page').append(relScript);
});

Loading 3rd party script overrides the styles of my site completely

When I load my page to check the remainder of gift card balance (from a 3rd party script) it overrides the styles that I have on my site. Below is an example of my code:
<div id="main" class="main">
<div id="giftcard-balance-container" class="giftcard-balance-container">
<div id="chockstone-loading" class="chockstone-loading">
<p>Loading...</p>
</div>
<script>
var container = document.getElementById('giftcard-balance-container');
while (container == null) {
setTimeout(function () {
container = document.getElementById('giftcard-balance-container');
}, 100);
}
var addListener = function (script, callback) {
if (callback !== null) {
if (script.readyState) { // IE, in¡cl. IE9
script.onreadystatechange = function onReadyStateChange() {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null;
callback();
}
};
} else {
script.onload = function onLoad() { // Other browsers
callback();
};
}
}
};
var scriptLoaded = function () {
var loading = document.getElementById('chockstone-loading');
loading.parentNode.removeChild(loading);
};
try {
var script = document.createElement('script');
script.src = 'SCRIPT_URL_REMOVED_FOR_SECURITY_REASONS';
container.appendChild(script);
addListener(script, scriptLoaded);
} catch (e) {
}
</script>
</div>
</div>
Is there a way to make it so the script doesn't override my styles that I currently have?
Use !important in your style
Example
.your-class{
color:#ffffff !important;
}

onclick return two functions (Tracking)

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 :)

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();

Programmatically include JQuery in high conflict environment -

I'm writing a snippet of code to be put on any third party website and have NO idea what environment it will be dropped into. My end goal is for the badge to be
<script src="http://example.com/js/badge.js"></script>
I would like to use jQuery in my badge code to make my life easier, but I don't want to require another include on the client side (getting anything updated on the client is a pain).
This is the best I could come up with. I don't want anything before or after my script to be affected with any leftover variables or weird collisions. Does anyone see any issues?
(function() {
function main($) {
// do stuff with $
$(document.body).css("background", "black")
}
// If jQuery exists, save it
var old_jQuery = null;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery.noConflict(true);
}
}
var addLibs = function() {
// Body isn't loaded yet
if (typeof(document.body) == "undefined" || document.body === null) {
setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
document.body.appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || jQuery("*") === null) {
setTimeout(checkLibs, 100);
return;
}
var new_jQuery = jQuery.noConflict(true);
jQuery = old_jQuery;
main(new_jQuery);
}
addLibs();
})();
I ended up going with http://yourock.paulisageek.com/js/popup.js . See the test (with console logging avialable) http://paulisageek.com/tmp/jquery-programatically.html. It doesn't reset jQuery and $ until jQuery actually finishes loading. Any way to block javascript without an infinite loop (which blocks the jQuery loading itself)?
// A namespace for all the internal code
var yourock = {};
// Include JQuery programatically
(function() {
// Don't let the script run forever
var attempts = 30;
// If jQuery exists, save it and delete it to know when mine is loaded
var old_jQuery;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery;
delete jQuery;
}
}
var addLibs = function() {
var head = document.getElementsByTagName("head");
if (head.length == 0) {
if (attempts-- > 0) setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
head[0].appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || typeof(jQuery) != "function" || jQuery("*") === null) {
if (attempts-- > 0) setTimeout(checkLibs, 100);
return;
}
yourock.jQuery = jQuery.noConflict(true);
if (typeof old_jQuery == "undefined")
jQuery = old_jQuery;
}
addLibs();
})();
This works:
(function(){
if (window.jQuery !== undefined) {
doStuff(jQuery);
} else {
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
var interval = setInterval(function(){
if (window.jQuery) {
clearInterval(interval);
var JQ = jQuery.noConflict(true);
doStuff(JQ);
}
}, 100);
}
})();
function doStuff($) { /* Do stuff with $ */ }
Including jQuery again will override the $ variable, which might be an older version of jQuery or another framework. You should probably save that too.
I don't have tested so much this code but it should work...
(function($, window) {
var version = ($ && typeof($) == 'function' && $().jquery ? ($().jquery).split('.').join('') : 0), // 1.8.1 -> 181
jBack = null;
if (version) console.log('jQuery current version : ', version);
else console.log('no jQuery');
var loaded = function() {
console.log('loaded()');
var $ = jQuery.noConflict(true); // LOCAL own jQuery version
if (jBack) {
window.$ = jBack; // Reassign ex-jQuery
window.jQuery = jBack;
}
// OK : now work with OUR new $
console.log('jQuery new version : ', $().jquery);
},
loadJs = function(jsPath) {
console.log('loadJs()');
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', jsPath);
s.onload = loaded;
document.getElementsByTagName('body')[0].appendChild(s);
};
if (version) jBack = $;
if (version < 180) loadJs('http://code.jquery.com/jquery-1.9.1.min.js');
else loaded();
})((typeof(jQuery) == 'function' ? jQuery : null), window);

Categories

Resources