I'm developing in javascript and would like to insert a script only if a condition is verified.
For example:
var a = exampleVariable;
if (a == conditionIwant) {
// append to head:
<script src="http://code.jquery.com/jquery-1.5.js"> </ script>
}; //or something like this
How can I insert jquery.js only if a condition is true?
This is really simple:
if(somethingIsTrue) {
var sc = document.createElement('script');
sc.src = 'http://code.jquery.com/jquery-1.5.js';
sc.type = 'text/javascript';
if(typeof sc['async'] !== 'undefined') {
sc.async = true;
}
document.getElementsByTagName('head')[0].appendChild(sc);
}
Related
I have added a random post button to my site (http://factowy.blogspot.com). I want to load random post as the page loads instead of clicking the button. How can I do that? Here is the code for the random post button.
<script type="text/javascript">
function showLucky(root){ var feed = root.feed; var entries = feed.entry || []; var entry = feed.entry[0]; for (var j = 0; j < entry.link.length; ++j){if (entry.link[j].rel == 'alternate'){window.location = entry.link[j].href;}}} function fetchLuck(luck){ script = document.createElement('script'); script.src = '/feeds/posts/summary?start-index='+luck+'&max-results=1&alt=json-in-script&callback=showLucky'; script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); } function feelingLucky(root){ var feed = root.feed; var total = parseInt(feed.openSearch$totalResults.$t,10); var luckyNumber = Math.floor(Math.random()*total);luckyNumber++; a = document.createElement('a'); a.href = '#random'; a.rel = luckyNumber; a.onclick = function(){fetchLuck(this.rel);}; a.innerHTML = 'Random Fact'; document.getElementById('abt-random').appendChild(a); } </script><script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
You need something like this.
<body onload='showLucky()'>
Go to Blogger > Layout > Edit HTML and replace <body> with above mentioned code and check.
It's just way you would call function on page load. I haven't tried with your function.
I was able to load random post with the following code:
window.onload = function(){fetchLuck(a.rel);}
I need to pass back a unique ID in place of "INSERT+ORDER+ID" for when a user clicks on our "Request Information" button to better track our visitors. Does anyone know how I can accomplish this? Any help would be much appreciated, thanks!
<script type="text/javascript">
var _qevents = _qevents || [];
(function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") +
".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scpt = document.getElementsByTagName('script')[0];
scpt.parentNode.insertBefore(elem, scpt);
})();
_qevents.push(
{qacct:"p-yeADJca0S9FXE",labels:"_fp.event.Request Information Confirmation
Page",orderid:"INSERT+ORDER+ID"}
);
</script>
<noscript>
<img src="//pixel.quantserve.com/pixel
/p-yeADJca0S9FXE.gif?labels=_fp.event.Request+Information+Confirmation+Page&
orderid=INSERT+ORDER+ID" style="display: none;" border="0" height="1" width="1" alt="Quantcast"/>
</noscript>
assuming you mean a random unique ID,
for the javascript event tracking this should work:
// function to generate random id in js
function getRandomId() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
var btnReqInfo = document.getElementById('request_information_btn');
// bind the click on button
btnReqInfo.addEventListener('click', function() {
// track the event
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage",orderid: getRandomId() });
, false);
About the content in the noscript tag, you can't do it with static html of course so you have to put in the context of your template (in the php file), something like this that generates a unique ID and then echo it in place of your placeholder.
Since I'm in the mood for structuring and cleaning, I took the liberty of refactoring a bit the code, in case, you can replace all your script with this (assuming you're using plain js (vanilla) and html 5):
<script>
var _qevents = _qevents || [];
(function() {
var
init = function() {
loadScript();
bindUi();
},
loadScript = function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scrpt = document.getElementsByTagName('script')[0];
scrpt.parentNode.insertBefore(elem, scrpt);
},
bindUi = function() {
var btnReqInfo = document.getElementById('request_information_btn');
btnReqInfo.addEventListener('click', track.order, false);
},
track = {
order: function() {
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage", orderid: utils.getRandomId() });
}
},
utils = {
getRandomId : function() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
};
init();
})();
</script>
I would suggest using an AJAX call that is binded to the onclick event or .click if you're using JQuery
The AJAX call would hit a PHP script or call whatever you're using for analytics.
I have 2 domains going to my site but I want to change the class of a div that has an ID of #logo.
I have tried the following but no luck...
<script type="text/javascript">
var hasChar1 = window.location.href.indexOf('domain01') != -1;
var hasChar2 = window.location.href.indexOf('domain') != -1;
if (hasChar1)
{
if (hasChar1)
{document.getElementById("logo").className = "logoNZ";}
else
{document.getElementById("logo").className = "";}
}
else if (hasChar2)
{document.getElementById("logo").className = "";}
</script>
Why inserting the same if statement inside itself?
This should work:
document.getElementById('logo').className = (window.location.hostname.indexOf('domain') !== -1) ? 'logoNZ' : 'notLogoNZ';
Make sure you place this code at the end of your body, after the div as already been rendered!
Have you tried something like this ?
if (window.location.hostname == "domain01"){
document.getElementById("logo").className = "logoNZ";
}
else if (window.location.hostname == "domain"){
document.getElementById("logo").className = "";
}
I trying to create iframe then add script to it and script will run. Iframe created, but it always get errors in process of appending script to that iframe. Please help.
<div align="center" id="adframe1">
<script type="text/javascript">
var response1 = '<script>var ad_unit="123";</scr'+'ipt><script src="http://abc.com/abc.js"></scr'+'ipt>';
$('<iframe id="adframe1mopub"/>').appendTo('#adframe1');
$('#adframe1mopub').ready(function() {
$('#adframe1mopub').contents().find('body').append(response1);
});
</script>
</div>
You can try this script:
HTML:
<div id=container-iframe></div>
JS:
var response1 = '<script>var ad_unit="123";</scr' + 'ipt><script src="http://abc.com/abc.js"></scr' + 'ipt>';
$('<iframe></iframe>', { id: 'adframe1mopub' }).bind('load', function(event) {
if (!this.contentWindow) {
return;
}
this.contentWindow.document.body.innerHTML += response1;
}).appendTo('#container-iframe');
But it would be best way to implement this:
$('<iframe></iframe>', { id: 'myiframe' }).bind('load', function(event) {
if (!this.contentWindow) {
return;
}
var scripWidthCode = document.createElement('script');
scripWidthCode.type ='text/javascript';
scripWidthCode.innerText = 'var ad_unit="123";';
this.contentWindow.document.getElementsByTagName('head')[0].appendChild(scripWidthCode);
var scripWidthSrc = document.createElement('script');
scripWidthSrc.type ='text/javascript';
scripWidthSrc.src = 'http://abc.com/abc.js';
this.contentWindow.document.getElementsByTagName('head')[0].appendChild(scripWidthSrc);
}).appendTo('#container-iframe');
test
For example:
<script>
$(document).ready( function() {
alert( $(this).getBelowElementToThisScript('form').id );
});
</script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
This code should show this message: IamTheNext
In addition, the solution needs to work with this example too:
<script src="getbelowelement.js"></script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
Thanks
Try this:
var form = $('script[src="getbelowelement.js"]').next();
But I would suggest using the forms id:
var form = $('#IamTheNext');
You could also try giving the script tag an id.
This kind of approach is dangerous; script should never depend that much on where it is in the page.
That said, the following works in Firefox and Chrome and should work in the major browsers (use at your own risk).
See it in action at jsBin. Both <script> ... and <script src="..."> approaches are shown in the same page.
$(document).ready( function () {
invocationsOfThis = (typeof invocationsOfThis == 'number') ? invocationsOfThis + 1 : 1;
var scriptTags = document.getElementsByTagName ('script');
var thisScriptTag = null;
//--- Search scripts for scripts of this type.
for (var foundCnt = 0, J = 0, L = scriptTags.length; J < L; ++J)
{
/*--- Since the script can be either inline or included, search
both the script text and the script src link for our unique
identifier.
*/
var thisTag = scriptTags[J];
var scriptCode = thisTag.innerText || thisTag.textContent;
var scriptSrc = thisTag.src;
//--- IMPORTANT, change pastebin.com to the filename that you use.
if (/invocationsOfThis/i.test (scriptCode) || /pastebin.com/i.test (scriptSrc))
{
//--- Found a copy of this script; is it the right one, based on invocation cnt?
foundCnt++;
if (foundCnt == invocationsOfThis) {
thisScriptTag = thisTag;
break;
}
}
}
if (thisScriptTag) {
//--- Get the target node.
var nextForm = $(thisScriptTag).next ('form');
var nextFormId = nextForm.attr ('id');
//--- Act on the target node. Here we notify the user
nextForm.text ('This is form: "' + nextFormId + '".');
}
} );