Display images from an array [duplicate] - javascript

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

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.

Flatten javascript array of objects with underscore.js

I have a javascript array of object that looks like this:
"partners":[{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}]
I would like to output the value of each array's key using the underscore library. So for each object, I'd like to output something that looks like this:
<h1>Username Value</h1><img src="profileImg Value here" />
A bit confused about your "source", but I think you're just trying to do this:
_.each(partners, function(p) { document.write('<h1>' + p.username + '</h1>\
<img src="' + p.profileImg + '" alt="' + p.username + '" />'); }
//substitute some DOM method (e.g. jquery().append) for document.write
Is this the result you're looking for?
this would only be applicable if your source looked more like:
var partners = [{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}];
EDIT:
var someBiggerObject = {
partners: [
{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}
]
};
_.each(someBiggerObject.partners, function(p) { document.write('<h1>' + p.username + '</h1>\
<img src="' + p.profileImg + '" alt="' + p.username + '" />'); }
//substitute some DOM method (e.g. jquery().append) for document.write
The right way to do this is _.template
Example
If your structure is like this:
var list = {"partners":[
{"username":"fangonk","profileImg":"fangonk.jpg"},
{"username":"jane","profileImg":"jane.jpg"},
{"username":"tom_jones","profileImg":"tom.jpg"}
]};
You can create the repeated item template (note type="text/html")
<script type="text/html" id="userItemTemplate">
<h1><%= username %></h1><img src='<%= profileImg %>' />
</script>
and put each item into the template via a loop
var uIT = $("#userItemTemplate").html();
_.each(list.partners,function(user){
$("#target").append(_.template(uIT,user));
});
OR
put the loop into your template
<script type="text/html" id="userTemplate">
<% _.each(partners,function(user,key,list){ %>
<h1><%= user.username %></h1><img src='<%= user.profileImg %>' />
<% }); %>
</script>
then push the whole array in
var uT = $("#userTemplate").html();
$("#target2").html(_.template(uT,list));
Note that I am using lodash instead of underscore. It's compatible for the most part, but I prefer lodash because the benchmarks are faster and the library is maintained well.

document.write nested in document.write

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.

Categories

Resources