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;
}
Related
I've being bashing my head around finding a working solution for this.
Goal is to create a text size switcher for people with poor eyesight.
I have created three span elements with classes small, medium and large.
And I have a piece of code that almost gets the job done but it needs that cookie part.
$(function() {
$(".font-toggle span").click(function() {
var size = $(this).attr('class');
$("body").attr("id", size);
return false;
});
});
How can i use cookies to save my selection and add it after page refresh ?
Have been reading many stackoverflow posts about setting cookies but all of them feature only one toggle. Here I have three.
JSFIDDLE HERE
Many thanks!
$(document).ready(function(){
$(".font-toggle span").click(function() {
var size = $(this).attr('class');
$("body").attr("id", size);
if($.cookie('mycookie') == 'valueOfCookie'){
$.cookie('mycookie', '');
}
else{
$.cookie('mycookie', 'valueOfCookie');
}
return false;
});
if($.cookie('mycookie') == 'valueOfCookie'){
$("body").attr("id", 'big-font');
}
else{
$("body").removeAttr("id");
}
});
#big-font{
font-size: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<div class="font-toggle">
<span class="big-font">
Button
</span>
</div>
<div>
Text To Show
</div>
Maybe this will work for you.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<script>
"use strict";
$(document).ready(function() {
let eyesight = $.cookie('eyesight');
if (eyesight != undefined) {
$("body").addClass(eyesight);
} else
setEyesight('medium'); // Default size
$(".font-toggle span").click(function() {
setEyesight($(this).attr('class'));
});
});
function setEyesight(size) {
let eyesight = $.cookie('eyesight');
if (eyesight != undefined) {
$("body").removeClass(eyesight);
$.removeCookie('eyesight');
}
$("body").addClass(size);
$.cookie('eyesight', size);
}
</script>
What about this?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<script>
"use strict";
$(document).ready(function() {
let eyesight = new Eyesight();
eyesight.initialize();
$(".font-toggle span").click(function() {
eyesight.set($(this).attr('class'));
});
});
function Eyesight() {
let self = this;
let name = "eyesight";
let current = null;
let _default = "medium";
let data = $.cookie(name);
// initialzie
this.initialize = function() {
if (data!= undefined) {
$("body").addClass(data);
current = data;
} else
self.set(_default); // Default size
// init cookie listener
self.listener();
};
// set eyesight function
this.set = function(size) {
if (data != undefined) {
$("body").removeClass(data);
$.removeCookie(name);
}
$("body").addClass(size);
$.cookie(name, size);
current = size;
};
// eyesight cookie listener function
this.listener = function() {
setTimeout(function() {
let cookie = $.cookie(name);
if (cookie != undefined && cookie != current)
self.set(cookie);
self.listener();
}, 100);
};
}
</script>
Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery. i am using jquerycdn variable to pass to the loadscript() when checkjquery() is false. But when i am passing still the jquery CDN is not loading. Same issue facing with the remaining files like bootstrap, D3.js, knockout.js etc. All these file CDN's are kept in one js file.
Please check the below code:-
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
Initialize.prototype.checkJQuery = function () {
if (window.jQuery) {
return true;
} else {
return false;
}
};
if (!this.checkJQuery ()) {
console.log("jquerynot available")
this.loadJQuery ();
if (!this.checkJQuery ()) {
throw "Error loading jquery"
}
} else {
console.log("jquery available")
}
Initialize.prototype.loadJQuery = function () {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function (src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.head.appendChild(my_awesome_script);
}
You need to give jQuery time to load before checking to see that it's loaded. An onload trigger would be better than timeout, but here's your code working.
function Initialize() {
var self = this;
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
if (!this.checkJQuery()) {
console.log("jquery not available")
this.loadJQuery();
setTimeout(function() {
if (!self.checkJQuery()) {
throw "Error loading jquery"
} else {
alert("jQuery loaded!");
}
}, 2500);
} else {
console.log("jquery available")
}
}
Initialize.prototype.checkJQuery = function() {
if (window.jQuery) {
return true;
} else {
return false;
}
};
Initialize.prototype.loadJQuery = function() {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function(src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.body.appendChild(my_awesome_script);
}
var i = new Initialize();
You might also look at this approach.
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();
I'm loading an image
obgImage.onload = function ( imageReady = true )
document.getElementById('vimeo').onload= function() {
videoReady = true;
}
What should i use to recognize when both of these are ready?
if(videoReady == true && pageReady == true){
$('#loading').fadeOut();
}
how do i make the if statement constantly check? I have query
var videoReady = false,
imageReady = false,
_ready = function() {
if (videoReady && imageReady) {
// do your code
}
else {
// waiting for the other onload function to be called
}
};
obgImage.onload = function () {
imageReady = true;
_ready();
};
document.getElementById('vimeo').onload= function() {
videoReady = true;
_ready();
};
Using this the ready function will be called two times if both elements will fire their onload function
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);