How to execute <script> code in a javascript append - javascript

I'm working with a plugin that is only Javascript. I need to have it dynamically create a DIV element with an advertisement in it.
I can't figure out why this doesn't work:
$(this).append('<div class="overlay-background">Advertisement
<script type="text-javascript">
GA_googleFillSlot("blog_landing_right_rectangle_300x250");
</script>'
It results in the element created with "Hello World" but it does not execute the GA-googleFillSlot function.

appending HTML into the DOM does not cause the browser to evaluate any script tags in said appended HTML.
If you really wanted to, you could evaluate the javascript by using eval():
eval($(this).find("script").text());

I know this is an old question but I've had a similar problem today.
The solution was using createContextualFragment.
My code looks something like this:
var tagString = '<script async type="text/javascript" src="path_to_script"></script>';
var range = document.createRange();
range.selectNode(document.getElementsByTagName("BODY")[0]);
var documentFragment = range.createContextualFragment(tagString);
document.body.appendChild(documentFragment);

This code works in my browser.
$('body').append('<script>alert("test");<' + '/' + 'script>');
so it might be that $(this) is what is actually causing your problem.
Can you replace it with 'body' and see if it works like that?

One workaround in your case could be to append a fake image with an onload event:
<img src="blank.gif" onload="GA_googleFillSlot('blog_landing_right_rectangle_300x250')" />

since your are in javascript, you can append and then execute the code:
$(this).append('<div class="overlay-background">Advertisement</div>');
GA_googleFillSlot("blog_landing_right_rectangle_300x250");

Please try:
s = '<' + 'script type="text-javascript">' +
'GA_googleFillSlot("blog_landing_right_rectangle_300x250");' +
'<' + '/' + 'script>';
$(this).append(s);
UPD: alas, this won't work, please use wless1's solution instead

Related

How do I use jQuery's insertBefore() function with a javascript string of HTML?

I am performing some DOM manipulation once my page loads and I was hoping to add some html right before an a specific div on the page. Not sure what I'm doing wrong here, I'm sure there's a simple way to accomplish this...
var finalStringHtml = '<div id="chartLinks">' + tableString + '</div>';
$(finalStringHtml.html().insertBefore("#chart_div")); //fails
$(toString(finalStringHtml).html().insertBefore("#chart_div")); //fails
You don't need the .html() call. (full docs: http://api.jquery.com/insertbefore/)
Try:
$(finalStringHtml).insertBefore("#chart_div");
If you want to, you can do the full code on one line and not create the variable:
$('<div id="chartLinks">' + tableString + '</div>').insertBefore("#chart_div");

Current location path as a url parameter

I need to put a link out from a corporate site to a surveymonkey survey. Our site uses a proprietary CMS limiting me from adding any proper function or third party plugin.
After evaluating options like those exposed in this other question, I believe I call the correct javascript function but everytime I open my CMS, the link duplicates itself... leading me to think I've done something inapropriate.
Things look acceptable on the JSFiddle demo I put together for this question but I'm hoping you'd have a more elegant solution in mind so I could try options !
<script type="text/javascript">
document.write("<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + " target='_blank'>Test - survey</a>");
</script>
Try this - it will probably not do what you want in one go, but it will hopefully isolate your problem so that you can better pinpoint what's going wrong:
HTML:
<div id="link"></div>
Javascript:
var SURVEYID = 3
var a = document.createElement("a");
a.innerHTML = "Test - survey";
a.href = "www.surveymonkey.com/r/"
+ SURVEYID
+ "?url="
+ window.location.pathname
+ "&target=_blank"
document.getElementById("link").appendChild(a)
I'm afraid there can be multiple things going wrong, but I hope you can now distinguish between the various parts that your URL is built up from.
This is mostly just a theory because I don't know your CMS or how it works, but I'm assuming that the CMS is inlining the javascript, executing it, and retaining that as its content along with the script. This would create that duplication. The original intent of using document.write I would assume was to completely replace the content; but if it's inlined, it only appends. An external script would completely replace. See below:
All of this text is retained.
<script type="text/javascript">
document.write("<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + "' target='_blank'>Test - survey</a>");
</script>
In this demo, we use document.body.innerHTML instead. This will replace the content completely.
None of this text will be retained.
<script type="text/javascript">
document.body.innerHTML = "<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + "' target='_blank'>Test - survey</a>";
</script>
If true, complete replacement of the body content is your goal, innerHTML is probably what you need.
Edit + Warning:
This may make the page inaccessible from the CMS depending on how it's built. It may make editing the page impossible.
Edit
Here's a better solution. Just set the href of the anchor by first getting it by the ID. This was based off of Sven ten Haaf's Answer.
<a href="#" id="__smlink" target='_blank'>Test - survey</a>
<script>
document.getElementById('__smlink').href = "https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname;
</script>

adding href using javascript append

Probably a rudimentary for some, but this is driving me crazy! I am not sure what I did wrong - I cannot/not allowed(?) to append a href - it is simply didn't get processed at all.
$('#lastViewed').append('<a href="/Path/To?_q="' + string + '>');
$('#lastViewed').append(.....some other stuffs.....);
$('#lastViewed').append('</a>');
I am trying to wrap the "other stuffs" with a
Thanks!
Edit
The complete line:
$('#lastViewed').append('<div id="id_' + x + '<a href="/PVProduct/ProductDetail?_productID=' + JSON.parse(localStorage.getItem("pid_" + x)).productID);
This is incorrect. You don't append() opening and closing tags like that. Instead, append() the whole tag. Or even better, create the a element and append() it:
$a = $('<a>').attr('href', yourHref).html(yourText);
$('#lastViewed').append($a);
you can use it
var link=document.createElement("a");
link.id="idName";
link.setAttribute("href", "your link");
document.appendChild(link);

How to get html to print return value of javascript function?

What is the preferred syntax to get html to print return value of javascript function?
function produceMessage(){
var msg= 'Hello<br />';
return msg;
}
EDIT: Yikes, too many answers without me clarifying what I meant. I know how to do it via the script tag. However, let's say I wanted to make the message red. Would I just encase the script tag inside my css like so?
<div style="color:red><script>document.write(produceMessage())</script></div>
I guess my main question was, should you be using document.write to get the return values to print?
There are some options to do that.
One would be:
document.write(produceMessage())
Other would be appending some element in your document this way:
var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);
Or just:
document.body.appendChild(document.createTextNode(produceMessage()));
If you're using jQuery, you can do this:
$(document.body).append(produceMessage());
It depends what you're going for. I believe the closest thing JS has to print is:
document.write( produceMessage() );
However, it may be more prudent to place the value inside a span or a div of your choosing like:
document.getElementById("mySpanId").innerHTML = produceMessage();
if you really wanted to do that you could then do
<script type="text/javascript">
document.write(produceMessage())
</script>
Wherever in the document you want the message.
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
Is a good example.
Or you can tell javascript where to write it.
<script type="text/javascript">
var elem = document.getElementById('myDiv');
var msg= 'Hello<br />';
elem.innerHTML = msg;
</script>
You can combine this with other functions to have function write content after being evaluated.
you could change the innerHtml on an element
function produceMessage(){
var msg= 'Hello<br />';
document.getElementById('someElement').innerHTML = msg;
}
Most likely you're looking for something like
var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();
provided that this is not something which happens on page load, in which case it should already be there from the start.

Use getElementById() on non-current HTML document

Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method

Categories