How to get text inside span, and use it into other script - javascript

let say..
<span id="Singer">Bieber</span>
I know by using DOM I can duplicate 'Bieber' to anywhere..
<script>
x=document.getElementById("Singer");document.write("<span>" + x.innerHTML + "</span>");</script>
..but id doesn't seems working when I want to insert the DOM script into the script below. Is there any way to put 'Bieber' into the script below?
<script language=JavaScript src="http://lyricfind.rotator.hadj7.adjuggler.net/servlet/ajrotator/275968/0/vj?z=lyricfind&dim=35518&click=&kw=<I WANT TO PUT BIEBER HERE>"></script>

The problem you have is the browser will be firing off the request for the script before it is able to access the span element. It could be done by dynamically inserting the script tag after the span is read:
window.onload = function(){
var x = document.getElementById("Singer");
var s = document.createElement("script");
s.src = "http://lyricfind.rotator.hadj7.adjuggler.net/servlet/ajrotator/275968/0/vj?z=lyricfind&dim=35518&click=&kw=" + encodeURIComponent(x.innerHTML);
s.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(s);
};
This assumes your page has a <head> section. If not, you could append to the body instead.

Related

Firing JavaScript generated link issue

I have issues firing this link (that triggers a script from Chargebee) when is added dynamically via JavaScript. When it's added directly in html it works normally.
The entire generated link is appearing correctly (populated with the variants) in browser when inspected just it doesn't fire.
Here are the pieces I have related to this:
The JavaScript part:
var checkout = document.getElementById("checkout");
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
checkout.innerHTML = link;
A simple div:
<div id="checkout"></div>
The script from chargebee:
<script src="https://js.chargebee.com/v2/chargebee.js" data-cb-site="site-name"></script>
Once you've loaded chargebee.js script it starts to look for a tag a with specific data-cb attributes. The script does it one time only. If the tag a did not exist in the DOM then, the script does nothing. When you add the tag a later that makes no effect at all, because a "discovery phase" is over.
If you want to have more control over chargebee initialisation process, you should go for "Checkout via API" option provided by the developers.
P.S. There are two hacky solutions:
You may load Chargebee script after adding tag a to the DOM.
function loadChargebee() {
var script = document.createElement("script");
script.src = "https://js.chargebee.com/v2/chargebee.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
var checkout = document.getElementById("checkout");
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
checkout.innerHTML = link;
loadChargebee(); // <=== add Chargebee.js
Leave the tag a in the DOM, load the script as usual but modify data attributes as needed after page load:
<a id="beecheckout" href="javascript:void(0)" data-cb-type="checkout" data-cb-1="" data-cb-2="" data-cb-3="">Order</a>
document.getElementById('beecheckout').setAttribute('data-cb-1','new data value');

How can I dynamically update and execute javascript code in my web page?

I have a website with a <script> tag
<script id='text1' type='text/javascript'></script>
that I insert some javascript code into from a <textarea>
<div id="text2">
<textarea class="text3"></textarea>
</div>
while executing some javascript
// get text from text area
obj = document.getElementById('text2').getElementsByClassName('text3');
var text = obj[0].value;
// assign to script tag
obj = document.getElementById('text1');
obj.text = text;
and on a button click it executes a function in a namespace from the <textarea> code
var namespace1 = {};
(function(context) {
context.getGameName = function() {
return ('text');
};
})(namespace1);
Everything works just fine, but if I attempt to change the text in the <textarea> and update the contents of the <script> tag, I can see in the console that the contents in the DOM are being updated, but when executing the code again on the button click, the old code is executed, not the new.
How can I update the javascript and execute the new version of a function with the same name?
A script tag content is evaluated when the node is first inserted in the DOM, not every time you change its content.
You need to create a new script tag with the new content, remove the old one and insert the new into the DOM.
var s = document.createElement("script");
s.textContent = "console.log('Hello,');"
document.body.append(s); // Will display "Hello," on console
document.body.removeChild(s);
s = document.createElement("script"); // <<-- create a new node
s.textContent = "console.log('world.');"
document.body.append(s); // Will display "world." on console
if you omit the second document.createElement call the "world." call will not be done.
To define a new version of the function with the same name, just redeclare it (below is one of ways):
var newScript = document.createElement('script');
newScript.innerHTML = document.getElementById('text2').getElementsByClassName('text3')[0].value;
document.body.appendChild(newScript);
You've no need to change the contents of some script tag you've included.

Loading different JS file for iPad only?

I am trying to load a different Javascript file if the site is viewed on ipad.
I have the following code but it puts the code in head section (between head tags) because of this line of code:
var h = document.getElementsByTagName('head')[0];
I was just wondering how I can place the code where ever I want i.e. between a div without name or at the bottom of the page instead of placing automatically in between the head tags?
<script language="javascript">
if (navigator.userAgent.match(/iPad/i) != null){ // may need changing?
var js = document.createElement('script');
js.type = "text/javascript";
js.src = "mainaPPiPad.js";
var h = document.getElementsByTagName('head')[0];
h.appendChild(js);
}
</script>
Thanks in advance
You need to change this line to point at another element in the document:
var h = document.getElementsByTagName('head')[0];
To append it to the end of <body>, you'd do:
var h = document.getElementsByTagName('body')[0];
Or to append it to <div id="foobar">:
var h = document.getElementById('foobar');
Just select the element via JavaScript and append it. For example:
<div id="magic-div"></div>
document.getElementById('magic-div').appendChild(myNode);

Javascript widget inside JQuery

We are using the Ning platform, and in order to add a new container DIV underneath the blog content (but before the comment section), we added the following before the body tag:
<script type="text/javascript">
if (typeof(x$) != 'undefined') {
x$("DIV.xg_module.xg_blog.xg_blog_detail.xg_blog_mypage.xg_module_with_dialog").after('<div>CONTENT GOES HERE </div>');
}
else{
}
</script>
However, then the content we need to load is javascript from an affiliate program, who sent us this code to add into that div:
<div style="width:750px;">
<div style="border-bottom:1px solid #FFFFFF;color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:22px;font-weight:bolder;margin-bottom:10px;padding-bottom:2px;text-transform:uppercase;">From Around the Web</div>
<script type='text/javascript'>
var _CI = _CI || {};
(function() {
var script = document.createElement('script');
ref = document.getElementsByTagName('script')[0];
_CI.counter = (_CI.counter) ? _CI.counter + 1 : 1;
document.write('<div id="_CI_widget_');
document.write(_CI.counter+'"></div>');
script.type = 'text/javascript';
script.src = 'http://widget.crowdignite.com/widgets/29949?_ci_wid=_CI_widget_'+_CI.counter;
script.async = true;
ref.parentNode.insertBefore(script, ref);
})(); </script>
</div>
And obviously, that does not work.
THE QUESTION: is there a better way to do this? Is it just a matter of all the conflicting 's and "s? Is there an easier way to format this or output it? Is it failing because it's simply not loading the javascript after the JQuery has already run post-page load? I have been trying different things and none seem to work and my eyes are ready to pop out of their sockets because I know there's something stupid I'm missing, so I thought I'd get some more eyes on it.
Thanks for any help/ideas/suggestions.
Try appending your new script element to the head element on your page. Most dynamic script loaders do this.
See Ways to add javascript files dynamically in a page for an example.

How in insert dynamic JavaScript tag into iframe

FINAL UPDATE: The second code block is working--I just miss-typed the URL.
I'm trying to place a dynamically created script into an iframe. I can access the head of the iframe, but it doesn't seem to accept the append request. The console log call returns the head tag, and the following append of text into the body works fine. I've also tried appending the script tag to the body. (note: the script tag is not on the same domain, so I've avoided using getScript or ajax).
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head")); // outputs: [<head></head>]
$(this).contents().find("head").append(script); // doesn't work
$(this).contents().find("body").append(script); // doesn't work
$(this).contents().find("body").append("Test"); // works
}).appendTo("#content");
});
Here is the new version that successfully appends the script based upon the suggestion below, but the script doesn't evaluate (as tested by a simple alert). Plus, another oddity: the "working" icon displays for about 15 seconds and the status (in chrome) says "retrieving..." Eventually it stops, but nothing happens.
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head"));
$(this).contents().find("head")[0].appendChild(script);
$(this).contents().find("body").append("Test");
}).appendTo("#content");
});
Update: When the cursor icon finally finishes working (about 10 seconds, which is odd because it's a local server with one line of code), I get this message in the Chrome console (it's in all red with a red circle "X" icon next to it):
GET http://cross-domain.com/script.js
(anonymous function)temp.html:16
jQuery.event.dispatchjquery-1.7.1.js:3261
jQuery.event.add.elemData.handle.eventHandlejquery-1.7.1.js:2880
jQuery.fn.extend.appendjquery-1.7.1.js:5771
jQuery.fn.extend.domManipjquery-1.7.1.js:5973
jQuery.fn.extend.appendjquery-1.7.1.js:5769
jQuery.each.jQuery.fn.(anonymous function)jquery-1.7.1.js:6162
(anonymous function)temp.html:18
jQuery.Callbacks.firejquery-1.7.1.js:1049
jQuery.Callbacks.self.fireWithjquery-1.7.1.js:1167
jQuery.extend.readyjquery-1.7.1.js:435
DOMContentLoaded
See this answer https://stackoverflow.com/a/3603496/220299
It may in fact be working, but the script tag is just not visible.
Try this.
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
$(this).contents().find("head").append('<scr' + 'ipt type="text/javascript" src="//cross-domain.com/script.js"></scr' + 'ipt>');
}).appendTo("#content");
});

Categories