I'm trying to append information to my page from two different JavaScript arrays. It looks like this.
var i = 0;
var videoArr=["big long array"];
var descriptArr=["big long array"];
function appendVideo(i) {
var url = "http://i.ytimg.com/vi/" + videoArr[i] + "/mqdefault.jpg";
$("#history").append("<img src=\"" + url + "\" width=\"120\" height=\"68\" />**NEED TO PRINT descriptArr[i] HERE**<br />");
}
function loadHistory() {
while (i < '.$length.') {
appendVideo(i);
i = i + 1;
}
}
So the above code is appending all the elements from the videoArr no problem. The problem is the descriptArr is full of free text descriptions that I need to print beside each videoArr element. What's he best way to do this? I presume it's not document.write(descriptArr[i])...
Try this, as long as you are sure that descriptArr does not contain any HTML literals.
$("#history").append("<img src=\"" + url + "\" width=\"120\" height=\"68\" />" + descriptArr[i] + "<br />");
Not the best way, but just try something like this
$("#history").append("<img src=\"" + url + "\" width=\"120\" height=\"68\" />" + descriptArr[i] + "<br />");
Ive used this for achieving the same thing:
aDate = (document.getElementById("datepicker").value);
$('.daysContain').find('div').eq(dateArray.length-1).prepend(aDate + '<br>');
Related
I'm writing my first code in an interactive/follow-along program through Cengage (MindTap). The program is instructing me to "write the HTML code for the inline element showing the sky image to use in the webpage." I am supposed to create a variable named imgStr that stores this text string:
<img src='sd_skyMap.png' />
Where Map is the value of the mapNum variable (there are 23 files titled sd_sky0, sd_sky1, sd_sky3 and so fourth). It says to use the + operator to combine text strings together and to include single-quote characters within the text strings.
I cannot get the sky images to appear on the webpage to save my life.
I've attempted going through a tutor provided through my university but have still have no luck getting the image to display.
var imgStr = "<img src='sd_sky0 + sd_sky1 + sd_sky2 + sd_sky3 +
sd_sky4 + sd_sky5 + sd_sky6 + sd_sky7 + sd_sky8 + sd_sky9 +
sd_sky10 + sd_sky11 + sd_sky12 + sd_sky13 + sd_sky14 + sd_sky15
+ sd_sky16 + sd_sky17 + sd_sky18 + sd_sky19 + sd_sky20 +
sd_sky21 + sd_sky22 + sd_sky23' + mapNum + '.png' />";
document.getElementById("planisphere").insertAdjacentHTML() = imgStr;
Having inserted the code into jshint.com, it stated one warning and one unused variable.
(Bad assignment.)
document.getElementById("planisphere").insertAdjacentHTML() = imgStr;
and mapNum is an unused variable.
InsertAdjacentHTML takes two strings as parameters.
The first parameter is the position which takes one of four static values.
The second parameter is your HTML string to be inserted.
An example for what you want could be:
document.getElementById("planisphere").insertAdjacentHTML('afterbegin', imgStr);
You were nearly there, just append beforeend using the document.insertAdjacentHTML()
const imgStr = `<img src='sd_sky0 + sd_sky1 + sd_sky2 + sd_sky3 +
sd_sky4 + sd_sky5 + sd_sky6 + sd_sky7 + sd_sky8 + sd_sky9 +
sd_sky10 + sd_sky11 + sd_sky12 + sd_sky13 + sd_sky14 + sd_sky15
+ sd_sky16 + sd_sky17 + sd_sky18 + sd_sky19 + sd_sky20 +
sd_sky21 + sd_sky22 + sd_sky23' + mapNum + '.png' />`;
document.getElementById("planisphere").insertAdjacentHTML('beforeend', imgStr);
<div id = "planisphere">
</div>
There are two problems on your code, the first is you need to run trough the different image files and add each one separately. On the code you provided, all image's names are being combined as one.
The second problem is your use of the insertAdjacentHTML() function. The function expects as arguments the position of the new tag and the tag itself, none is being passed. Check here for a better explanation.
Assuming you have n images that you want to add as n tags, you can try something like this:
// variable to hold the total number of images used
var numberOfImages = 23;
// we loop trough all images, where i will count from 0 to numberOfImages
for (var i = 0; i < numberOfImages; i++) {
// on each step of the loop we add a new img tag with sd_skyi as source
document.getElementById("planisphere")
.insertAdjacentHTML('afterend', "<img src='sd_sky" + i + ".png' />")
}
If you use this exerpt as is, it will add 23 img tags to an element with id planisphere.
So I have this code and would like to know how I could go ahead to put my javascript var into this string. I cannot seem to make a working code for myself.
For the image source i want picture.value to be in there. I have tried different solutions but have not managed to work it out myself. All help is greatly appreciated
var text = "<img src="">
I have currently been trying var text = "<img src=" + picture.value +">
but that doesn't seem to work for me.
You cannot use " & ' this together unless you escape it with a \.
var text = '<img src="' + picture.value + '">'
OR
var text = "<img src=\"" + "Hi" + "\">"
Try using ES6 new feature called Template literals (using quote). It is more cleaner and simpler.
var picture = {'value':'test-src-location'};
var text = `<img src="${ picture.value }">`;
console.log(text);
Assuming your picture.value is not empty.
var text = '<img src=' + picture.value + '>';
Example: https://jsfiddle.net/no293etL/
My question is this, if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Not sure if I can do this, but I'm hoping I can. What I have is a bit of javascript code that is taking data from an xml document. I have a list of 500+ cards that I have parsed through and stored by categories that are used often. Here are the relevant functions as they apply to my question.
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
Where node is the position within the list of cards, and due to the formatting of the document which I started with contains each card alphabetically by name, rather than numbered logically within sets.
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
Here is what I am using to populate a list of cards, with names that upon hovering over will display a card image.
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
What I am trying to do is retrieve the id of the element with the onmouseover event so that I can retrieve everything that is not being saved to a value.
I realized I can pass the id as part of the changeImage function as a temporary workaround, though it involves rewriting my toLink function and my changeImage function to include a second argument. As a married man, I've enough arguments already and could do with one less per card.
In summary, and I suppose all I needed to ask was this, but is there a way using only javascript and html to retrieve the id of an element, onmouseover, so that I may use it in a function. If you've gotten through my wall of text and code I thank you in advance and would appreciate any insights into my problem.
if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Yes, if you can change the link (and it looks like you can):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
Note the new argument this. Within changeImage, you'd get the id like this:
function changeImage(foo, element) {
var id = element.id;
// ...
}
Looking at your code, you'd update this line of toLink:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
Of course, you could also just put the id in directly:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
And then changeImage would be:
function changeImage(foo, id) {
// ...
}
I didn't use quotes around it, as these IDs look like numbers. But if it's not reliably a number, use quotes:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";
I have the following code:
$("#stats-list")
.append("<li>Elapsed: " + ajaxElapsed + "</li>\n" +
"<li>Display: " + tableElapsed + "</li>\n" +
"<li>Total: " + (ajaxElapsed + tableElapsed) + "</li>");
This was originally three appends that I concatenated into one. Is there anything I could do with jQuery that would clean up this code even more. What I was wondering was if jQuery has any string formatting with tokens that I could use.
function format(formatString) {
var args = Array.prototype.slice.call(arguments,1);
return formatString.replace(/\{(\d+)\}/g, function(match, num) {
return args[Number(num)];
});
}
format("<li>Elapsed: {0}</li>\n<li>Display: {1}</li>\n<li>Total: {2}</li>",
ajaxElapsed, tableElapsed, ajaxElapsed + tableElapsed);
afaik there is none built-in, but a powerful templating-subsystem, see jQuery Templates
just for completeness, i think this could be done more elegant:
var list = $('#stats-list');
$('<li />').text('Elapsed: ' + ajaxElapsed).appendTo(list);
$('<li />').text('Display: ' + tableElapsed).appendTo(list);
$('<li />').text('Total: ' + (ajaxElapsed + tableElapsed)).appendTo(list);
If you have many items you can do something like this to avoid missing + and writing li so many times. You can add any number of items inside the array and they will be joined with lis appropriately.
var list = '<li>' + [
'Elapsed: ' + ajaxElapsed,
'Display: ' + tableElapsed,
'Total: ' + ajaxElapsed + tableElapsed
].join('</li><li>') + '</li>';
$("#stats-list").append(list);
As a note I wouldn't use \n. li is a block element by default, so you'd be better styling it with css.
I have this <ul>
<ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul>
This javascript code which is meant to go throug a JSON object and add the options
to the UL:
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
});
If I do console.log() I can see that the looping is working. If I do:
console.log($("#select_opts").html());
It shows the HTML being updated as expected. However in the browser window, it shows the
UL as empty!
What am I doing wrong?
$("select_opts").append(str);
should be
$("#select_opts").append(str);
you're referring to object by id so you missed #
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
// ^
}
I can't really see what's wrong, but try this instead, just to see if it works...
$(str).appendTo("#select_opts");
Both should work.
Is this a typo?:
$("select_opts").append(str);
Did you mean?:
$("#select_opts").append(str);
UPDATED:
Try this:
$.each(q.opts, function(i, o) {
var li = $('<li>').attr('id', 'li_' + i);
var in = $('<input>').attr('type', 'text').attr('id', 'opt_' + i).val(o.option);
var aa = $('<a>').attr('href', 'javascript:delOpt(' + i + ');').text('Delete');
li.append(in).append(aa)
$("#select_opts").append(li);
});
The tag Input should be closed - if don't, when using not valid html in append() on Internet Explorer, the div is not put into DOM tree, so you cannot access it with jQuery later.
I'd imagine input needs to be properly self-closed.
I found the bug, another part of the code was emptying the <ul> when i clicked a certain button.