document.write nested in document.write - javascript

I have an ad tag that a third party is trying to stuff inside of a 'document.write' function and it's not working because the ad tag itself also contains document.write's. Is there a way to shove this ad tag inside of a single instance of document.write? If so, please help me figure this out and if not, is there an alternative?
<script type='text/javascript'>
var m3_u = 'http://this.that.com/adtag.js';
var m3_r = Math.floor(Math.random() * 99999999999);
var category='999';
if (!document.MAX_used)
document.MAX_used = ',';
document.write("<scr" + "ipt type='text/javascript' src='" + m3_u);
document.write("?c=" + category +"&b=Sampletag&p=ptnr&key=4984cc8f3064e22a4e29fb2b3b2e9cb5");
document.write('&cb=' + m3_r);
if (document.MAX_used != ',')
document.write("&exclude=" + document.MAX_used);
document.write(document.charset ? '&charset=' + document.charset :
(document.characterSet ? '&charset=' + document.characterSet : ''));
document.write("&loc=" + escape(window.location));
if (document.referrer)
document.write("&referer=" + escape(document.referrer));
if (document.context)
document.write("&context=" + escape(document.context));
if (document.mmm_fo)
document.write("&mmm_fo=1");
document.write("'><\/scr" + "ipt>");
</script>

document.write is often concidered a harmful method, as it directly inserts content into the document file itself. You should edit the innerHTML of the tag where you want to insert the code, although I've heard that directly using innerHTML isn't the correct way either. The method is called insertNode, If I'm remembering correctly, but I'm not sure, because I'm usually abstracting this type of problem away using frameworks such as jQuery, where it is as simple as
$("#myelement").html("<script>...</script>")
I hope that some of my fellow SO members can make this post more precise, I'll look some stuff up myself, but concider this to be my quick answer.

Related

Javascript function call from html

I'm doing javascript homework(total newb) and the study guide says...
Add document.write() statements around each line of HTML code (p. 53 gives an example)
Be sure to keep the code organized and easy to read.
Keep in mind that single (') and double (") quotes must be nested to avoid errors.
I've done that here.
function displayHeader() {
document.write("<h1>
<img src="images/PeteBanner.jpg" alt="Pistol Pete" />
Jason Lemon's Javascript Website!
<img src="images/PeteBanner.jpg" alt="Pistol Pete" /></h1>;
};
When I go to the header section of the html file...I'm supposed to call the function. I referenced the javascript file in the head section. Here is what I'm putting in the header section. It's not working. I know my code is way off.
It should look more like this ...
function displayHeader() {
document.write(
'<h1>' +
'<img src="images/PeteBanner.jpg" alt="Pistol Pete" />' +
'Jason Lemon\'s Javascript Website!' +
'<img src="images/PeteBanner.jpg" alt="Pistol Pete" />' +
'</h1>';
)
}
... but using document.write is generally bad practice, but if that's what the assigment says, I guess it's okay, just know that you shouldn't be using it.
To call the function after you've included the script in your HTML, you can do
<script type="text/javascript">
displayHeader()
</script>
Use one line.
function displayHeader() {
document.write('<h1><img src="images/PeteBanner.jpg" alt="Pistol Pete" />Jason Lemon\'s Javascript Website! <img src="images/PeteBanner.jpg" alt="Pistol Pete" /></h1>')
};
You need to concat the strings or write all in one line. Like this it would look like if you concatenate the strings.
function displayHeader() {
document.write(
"<h1> "
+ "<img src = 'images/PeteBanner.jpg' alt = 'Pistol Pete' / >"
+ "Jason Lemon 's Javascript Website!"
+ "<img src = 'images/PeteBanner.jpg' alt = 'Pistol Pete' / > </h1>"
);
};

Prepending constructed variable to HTML in JS

I started learning web developing for fun a couple weeks ago and I'm creating a rock-paper-scissors game using HTML, CSS and JS. I'm trying to add something to a block of HTML, but failing to do so with my current code. After a lot of googling I decided to try posting my question.
I added the function I'm trying to add the lines from and the place I'm trying to add them to. As I said, my code is not working and I don't quite understand why.
function displayPlayedRounds(winner) {
"use strict";
// <p class="roundCountPrev">
// <img src="/images/whiteRock.png" class="player1PrevRound"/>
// ← Round 4
// <img src="/images/blackPaper.png" class="player2PrevRound"/>
// </p>
var middlePart, toAppend;
if (winner === -1) {
middlePart = "Round " + movesMade + " →";
} else if (winner === 1) {
middlePart = "← Round " + movesMade;
} else {
middlePart = "Round " + movesMade;
}
toAppend = "<p class='roundCountPrev'><img src=" + userImages[userChoice] + " class='player1PrevRound'/>" + middlePart + "<img src=" + compImages[compMove] + "class='player2PrevRound'/></p>";
document.getElementById('displayPrevRounds').prepend('toAppend');
}
<span id='displayPrevRounds' class="player1">Previous rounds
<p class="roundCountPrev">
<img src="/images/whiteRock.png" class="player1PrevRound"/>← Round 4
<img src="/images/blackPaper.png" class="player2PrevRound"/>
</p>
</span>
firstly, as #madalin ivascu says, prepend is a jQuery function, not comes from DOM methods.
if you want use jQuery, it does a convenient way, you need "import/require/include" jQuery first. like:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
then, you can use this:
$('#displayPrevRounds').prepend(toAppend);
note that, no '', it's a var not chr.
if you want use DOM methods anyway, you can...
actually, i found you question via Google:"document html prepend",
use DOM Method:
parentNode.insertBefore(newChild, refChild);
How can I implement prepend and append with regular JavaScript?
and, here:
Append and Prepend without JQuery?
prepend is a jquery function, create a jquery object
$('#displayPrevRounds').prepend(toAppend);

Javascript breaks other script

Whenever I add the code below as a widget to my blog, the slider (Welcome...) on it will stop working. The slider should scroll through a few different images. I've read that 'no.conflict' will fix this problem but for the life of me haven't a clue where to put the code.
Recent Videos Widget
<script src='http://code.jquery.com/jquery-latest.js' type='text/javascript'></script>
<style type="text/css">
div.PBTytC {clear:both;padding:5px;font-size:12px;}
div.PBTytC.odd {background-color: #;}
div.PBTytC_thumb {position:relative;float:left;margin-right:8px;line-height:1;}
div.PBTytC_thumb img {width:76px;height:78px;border:0px solid #55A66B;}
div.PBTytC_title {font-weight:none;}
</style>
<script type='text/javascript'>
var PBTYoutubeUserName = "XXX";
var PBTYoutubeMAXResults = 3;
var PBTYoutubeAllow = "";
var PBTYoutubeDisallow = "";
var PBTYoutubeWgetIsEmpty = "No entries";
$(document).ready(function() {
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=58c841d14337ba4fbf693abd9701dc49&_render=json&max-results="+PBTYoutubeMAXResults+"&allow="+PBTYoutubeAllow+"&disallow="+PBTYoutubeDisallow+"&user="+PBTYoutubeUserName+"&_callback=?", function(response) {
var htm = "";
for(var i=0;i<response.count;i++) {
var item = response.value.items[i];
htm += '<div class="PBTytC';
if(i%2 == 1) htm += ' odd';
htm += '"><div class="PBTytC_thumb"><a target="_blank" href="' + item.link + '"><img title="' + item.title + '" src="' + item.thumb + '"/></a></div>';
htm += '<div class="PBTytC_title"><a target="_blank" href="' + item.link + '">' + item.title + '</a></div>';
htm += '<div class="PBTytC_description">' + item.description + '</div><div style="clear:both;"></div></div>';
}
if(htm == "") htm = PBTYoutubeWgetIsEmpty;
$("#PBTytWdtLoad").html(htm);
});
});
</script>
<div id="PBTytWdtLoad">Loading...</div>
Here is the link to my blog: Link
Thanks for reading and hopefully helping me out.
Including JQuery twice can cause issues. The code fragment above and your blog both have a script tag for query. Try adding it to your blog without including JQuery again.
As for the plugin not working:
Your site includes JQuery; Then it has a lot of scripts that use JQuery; Then it has a script that changes the JQuery operator so that $ isn't use since this will cause conflicts with other scripts using the variable $ in another way. Considering the amount of scripts on your site I'm surprised you don't have more issues.
Anyway after your last script tag you can't use $ in your scripts you have to use jQuery instead. For example:
jQuery(document).ready(function() {
jQuery.getJSON("http://pipes.yahoo.com/pipes/pipe.run?
If you go through your whole script and change '$' to 'jQuery' then that will help with your script where it is in your page now, with the current page listed at your blog.
Really though, this is just putting a band-aid on a bigger problem. It's worth thinking about what scripts you really need.

Display images from an array [duplicate]

This question already has answers here:
How to add a list of images to the document from an array of URLs?
(2 answers)
Closed 7 years ago.
I am trying to display six images from a javascript array. Running the code below I get no results it simply seems to be not working. I have no idea where my fault is.
Here is the javascript code:
var backgroundImage = new Array();
backgroundImage[0] = "images/colors-wallpaper.jpg";
backgroundImage[1] = "images/florida-birds.jpg";
backgroundImage[2] = "images/focus-on-life.jpg";
backgroundImage[3] = "images/set-into-life.jpg";
backgroundImage[4] = "images/dandelion.jpg";
backgroundImage[5] = "images/flowers.jpg";
backgroundImage[5] = "images/flowers.jpg";
function displayAllImages() {
// Here has to be some error!!! //
for (i=0;i<backgroundImage.length;i++) {
document.write("<li><img src='" + backgroundImage[i] + "' width="160" height="120"/><span>" + backgroundImage[i] + "</span></li>");
}
}
And that's my html code:
<html>
<head>
<script type="text/javaScript" src="changebackground.js"></script>
</head>
<body>
<div id="container">
<div class="backgoundImage">
<ul>
<script>displayAllImages();</script>
</ul>
</div>
</div>
</body>
</html>
Change
width="160" height="120"
to
width='160' height='120'
In
document.write("<li><img src='" + backgroundImage[i] + "' width="160" height="120"/><span>" + backgroundImage[i] + "</span></li>");
You are using wrong quotation marks
Your last array item key should be 6 (also I reckon as same value it's a copy/paste error) and I would strongly recommend against using document.write for such thing. Check link to see what I think you want to achieve but done in a slightly cleaner way (demo using jQuery just for the dom ready handling)
http://jsfiddle.net/UnFUB/
You need to escape your double quotes, see below:
document.write("<li><img src='" + backgroundImage[i] + "' width=\"160\" height=\"120\"/><span>" + backgroundImage[i] + "</span></li>");
document.write("<li><img src='" + backgroundImage[i] + "' width='160' height='120'/><span>" + backgroundImage[i] + "</span></li>");
You have a mistake in quotes. But better do not use document.write
The beeter way is to create an element in memory, and then put it in this block. How it looks on jQuery

How to reload JSON with AJAX every 10 Seconds

I'm trying to reload a JSON file every 10 seconds with JQUERY.
The page is here: http://moemonty.com/chirp/chirp.html
The Code is here:
<html>
<head>
<title>the title</title>
<!-- included Jquery Library -->
<script type="text/javascript" src="./js/jquery-1.4.2.js"></script>
<!-- jquery library -->
</head>
<body>
<script>
$.ajaxSetup({ cache: false }); //disallows cachinge, so information should be new
function loadChirp(){ //start function
var url = "http://www.chirpradio.org/json";
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data){
console.log(data.query.results.json);
document.write('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
document.write('The artist is: ' + data.query.results.json["record-label"] + '<br/><br/>' );
document.write('The album is: ' + data.query.results.json.album + '<br/><br/>');
document.write('The record label is: ' + data.query.results.json["record-label"] + '<br/><br/>');
document.write('The feedback link is: ' + data.query.results.json["feedback-link"] + '<br/><br/>');
document.write('The database id is: ' + data.query.results.json["database-id"] + '<br/><br/>');
document.write('The time is: ' + data.query.results.json.timestamp.time + ' ');
document.write(data.query.results.json.timestamp["am-pm"] + '<br/><br/>');
document.write('The current dj is: ' + data.query.results.json["current-dj"] + '<br/><br/>');
setTimeout("loadChirp()",5000);
alert('The timeout was triggered.');
});
} //end function
$(document).ready(function(){
//DOCUMENT READY FUNCTION
loadChirp();
});
//DOCUMENT READY FUNCTION
</script>
</body>
</html>
It doesn't seem to be working.
You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:
<div id='content'></div>
<script>
function loadChirp(){
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data) {
$('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
});
setTimeout("loadChirp()",5000);
}
</script>
etc...
I would expect the loop to work as quoted, but there could be a subtlety around the fact you're using JSONP. I would change the setTimeout call to:
setTimeout(loadChirp, 5000);
...for a couple of reasons. First off, using the function reference rather than a code string is a better idea generally, and second off, you're quite certain that you're getting the right function reference (whereas with the string, what reference you get depends on the context in which the code is executed).
But as Pointy pointed out in a comment, there's a separate issue: document.write will not do what you probably want it to do there. You can only use document.write to write to the HTML stream that's being parsed as part of the original page load. After the page load, you can't use it anymore. Consider using jQuery's append or appendTo and similar functions to add to the DOM after page load.
You have an error in console.log(data.query.results.json); - console is not defined.
Also, you can use setInterval( "function()", 5000 );.
You should definitely use:
setInterval("loadChirp", 10000):
Don't write loadCrirp() inside setInterval as we're only passing a refrence

Categories

Resources