I am using JavaScript to build a dynamic HTML page, here is my code:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append("<img src=\"" + getImage(images[i])+" \"width=\"90\"");
}
The getImage function returns an image...My question, how can I with JavaScript or Jquery in each iteration change the attribute of that current line, for example changing width or any image attribute of that current line in my getImage function . If I use $('this') it returns the object, but not in reference to that current line. Can I change those things in every iteration inside that function? so as a result I would get:
<img src="1.jpg" width="20">
<img src="2.jpg" width="90" >
function getImage(i) {
// some code
// WANT TO CHANGE HERE THE IMG ATTRIBUTE OF <img src "" width="">
return image ;
}
The idea of course is to change many more attributes...
If you want to be able to change the image attributes from within getImage then you should not use string-concatenation to build the image-tag.
Try something like:
for (var i = 0; i < images.length; i++) {
$("#a1").append(getImage(images[i]));
}
with:
function getImage(input) {
var $img = $('<img>').attr({
src: '%your-source%', // maybe from input?!
width: 100
});
// do other stuff with $img as needed
return $img;
}
You can't do that as you have it now. As far as I understand, getImage simply returns an URL to an image. And it can't modify width of img tag. You can do it like that:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append("<img src=\"" + getImage(images[i]) + " \"width=\"" + images[i].width + "\"");
}
assuming that your images array contains objects with fields src and width
Or you should make your getImage return whole img tag HTML:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append(getImage(images[i]));
}
function getImage(index) {
// some code
return "<img src=\"" + image + " \"width=\"" + width + "\"";
}
This may have some mistakes but i just want to share an idea of how you could do this in another way.
for (var i = 0; i < getImage.length; i++) {
$("#a1").append(getImage(images[i]));
}
function getImage(i) {
var s = // get the src
var w = // width based on i
return "<img src=\"" + s+ " \"width=\"" + w+ "\"" ;
}
Related
I just came the ID3 API across to get the cover of an audio file.
The base64 which is created by the API really good cannot be declarated in a img tag's src. The script don't even try to set a new src for the img tag.
https://github.com/aadsm/JavaScript-ID3-Reader
Here is my try:
<a class="uploaded_file"><img src="/symbol/audio.png"></a>
function getAudioCover(url) {
var tags = ID3.getAllTags(url);
var image = tags.picture;
if (image) {
var base64String = "";
for (var i = 0; i < image.data.length; i++) {
base64String += String.fromCharCode(image.data[i]);
}
var base64 = "data:" + image.format + ";base64," +
window.btoa(base64String);
return base64;
}
else {
return "/symbol/audio.png";
}
}
var uploadedFiles = 0;
var file_cover;
ID3.loadTags("audio.mp3", function() {
file_cover = getAudioCover("audio.mp3");
console.log(file_cover);
}, {
tags: ["picture"]
});
$('.uploaded_file:eq(' + uploadedFiles + ')').find('img').attr("src", file_cover);
The console gives me this out: https://jsfiddle.net/f1wzbtyh/
How do I get this working?
Is there a overflow of string length for jquery or for src attribute?
Place call to .attr() within callback function. file_cover may not be defined when referenced outside of .loadTags call.
ID3.loadTags("audio.mp3", function() {
file_cover = getAudioCover("audio.mp3");
console.log(file_cover);
$('.uploaded_file:eq(' + uploadedFiles + ')')
.find('img').attr("src", file_cover);
}, {
tags: ["picture"]
});
var out = [];
out.push('<div class="newData">');
for (var i = 0; i < 5; i++) {
out.push('<img src="' + data.data[i].images.low_resolution.url + '"/>');
count++;
// if (data.pagination.next_url = "") flag++;
if (count > 4) {
myurl = data.pagination.next_url;
count = 0;
}
out.push('</div>');
$('#wrap').append(out);
I have this simple code but in inspect elements it shows.
<div id="wrap">
<div class="newdata"></div>
<img scr='"asd"/>
<img scr='"asd"/>
<img scr='"asd"/>
</div>
Why is is immediately closing the newdata div and why not putting photos in it?
Try using a string ,don't forget to close the for loop
var out = '';
out+='<div class="newData">';
for (var i = 0; i < 5; i++) {
out+='<img src="' + data.data[i].images.low_resolution.url + '"/>';
count++;
// if (data.pagination.next_url = "") flag++;
if (count > 4) {
myurl = data.pagination.next_url;
count = 0;
}
}
out+='</div>';
$('#wrap').append(out);
You have the div '<div class="newData">' start outside the for loop and you close it inside the for loop. Then you add it inside the loop. Make sure you add valid html when you append it to #wrap, then it will work.
Edit: Additionally as others have pointed out: use strings to add the strings to each other and then append.
The issue is because you can only append whole elements to the DOM. When you append the opening div tag, the browser will automatically close it for you. This means your img elements are then created as siblings.
You could instead change your logic to create the div container, then build the HTML string in a loop and append that together. Try this:
var $div = $('<div class="newData"></div>').appendTo('#wrap');
var html = '';
for (var i = 0; i < 5; i++) {
html += '<img src="' + data.data[i].images.low_resolution.url + '"/>');
}
$div.append(html);
You are not closing the loop, that causing you the problem
out+='</div>';
$('#wrap').append(out);
add this in last of your loop
I have been struggling to find a way in which I could sort Divs after being displayed .So far, I have used prepend() and append() and I have managed to show at first the players that are streaming, but the next divs are random. I want to be able to show who's online, who's not and who has closed the account in order.
I have already tried deferred method: $.when(makeDivs()).then(sortDivs());
but it's not working properly, any idea how I can fix this?
My codepen: http://codepen.io/diegomdzr/pen/vKWGbd
I don't have the reputation to comment yet. But from my understanding, you want to make the classNames of divs in alphabetical order after they have been applied to the document?
function reOrder() {
var div = document.getElementsByTagName('div');
var cn = []; //ClassNames of each div.
for (var i = 0; i < div.length; i++) {
cn.push(div[i].className);
}
cn = cn.sort(); //sort the array in alphabetical order.
var oDiv = [];
for (var i = 0; i < cn.length; i++) {
//for each array item in cn, find where it's element is, remove the element, continue.
for (var ii = 0; ii < div.length; ii++) {
if (div[ii].className == cn[i]) {
oDiv.push(div[ii]);
var newDiv = [];
for (var iii = 0; iii < div.length; iii++) {
//Remove the element from the array.
if (div[iii] != div[ii]) {
newDiv.push(div[iii]);
}
}
div = newDiv;
}
}
}
return oDiv;
};
reOrder();
This will return an array of the elements, but sorted. You can then replace all of the elements of the document with these sorted elements.
Sorting is expensive, should be avoided if possible, and isn't a particularly good solution here.
It's way simpler to create a container (div) for each of your streamer categories, (online|offlie|nonExistent) then simply append HTML, as it is generated, to the appropriate container.
$(document).ready(function() {
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "comster404", "brunofin", "HorussTV"];
var link = "https://twitch.com/";
// Create/append containers here (or hard-code them in HTML) ... in correct order of presentation within #streamers.
var $onlineStreamers = $("<div/>").appendTo($('#streamers'));
var $offlineStreamers = $("<div/>").appendTo($('#streamers'));
var $nonExistantStreamers = $("<div/>").appendTo($('#streamers'));
streamers.forEach(function getStatus(element) {
$.getJSON("https://api.twitch.tv/kraken/channels/" + element + "?callback=?", function(json) {
var img = json.logo || "http://res.cloudinary.com/djnwhbm1z/image/upload/v1468187598/unknown_i7m43p.png";
$.getJSON("https://api.twitch.tv/kraken/streams/" + element + "?callback=?", function(json) {
// Append HTML to the appropriate container
if(json.stream) {
$onlineStreamers.append('<div class="online"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span><b>Game:</b></br>' + json.stream.game + ' </br><b>Status: </b>' + json.stream.channel.status + '</span></div></div>');
} else if(json.status == 422) {
$nonExistantStreamers.append('<div class="nonExistant"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span>Account Closed</span></div></div>');
} else {
$offlineStreamers.append('<div class="offline"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span>Offline</span></div></div>');
}
});
});
});
});
Notes:
No sorting required unless the entries need to be sorted within each category.
You can probably purge class="online" etc from the appended HTML, unless those classes are used elsewhere.
I need to add images to a given table. I have the following code:
HTML:
<div class="container" id="game"></div>
Javascript
function table() {
var i,
x,
domRow,
domCol,
rows = $("#rows").val(),
colums = $("#columns").val(),
table = $('<table>'),
cellId = 0;
table.empty();
for(i = 0; i < rows; i++) {
domRow = $('<tr/>');
for(x = 0; x < colums; x++) {
domCol = $('<td/>',{
'id': "cell-" + cellId++,
'class': "cell",
'text': 'cell',
'data-row': i,
'data-col': x
});
domRow.append(domCol);
}
table.append(domRow);
}
return table;
}
Now I want do add images to each data cell from another function.
Example:
function images() {
var game = $("game");
// TODO the images need to be added too
game.append(table())
}
An image with the name 0.png needs to be added to the data cell with the id="cell-0" and so on... (1.png to id="cell-1")
How could I do this?
The jQuery append method can take a function that returns the HTML string to append. And within that function this refers to the element. So you can just find all the td elements in your table and append the right image to each one:
function images() {
var game = $("game");
var tableEl = table();
tableEl.find('td').append(function () {
// `this` is the <td> element jQuery is currently appending to
var num = this.id.split('-')[1];
return '<img src="' + num + '.png" />';
});
game.append(tableEl)
}
Try setting window.myTable or similar to the output of table(), and then edit the table by acessing it from window.myTable.
For adding the images, what I would instead recommend is just inserting:
var img = $('<img>');
img.attr('src', parseInt(cellId) + ".png");
img.appendTo(domCol);
Right before domRow.append(domCol); (I did not test this).
Here is a simple code to add your images in each cell that its id correspond.
$('[id^=cell-]').each(function() {
var curCell = $(this);
curCell.html('<img src="' + curCell.attr('id').substring(5) + '.png">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr><td id="cell-0">1</td><td id="cell-1">2</td></tr>
</table>
I have a problem with listview.
I'm filling the list with an array, this list is completely custom, and I want that if an element of this array begins with "-R", then that cell must be different from the others (color, font, etc.).
the problem is that I can not take the index of the cell that begins with "-R".
this is the code:
arrayEserCardio = "try;find;-Reply;Again;"
var indexEserSplit = arrayEserCardio.toString().split(";");
for (var i =0; i<indexEserSplit.length;i++) {
var eserSingle = indexEserSplit[i];
var link_markup ='<li id="listCardio2"><a onclick="rowSelectedEserCardio()" href="#" class="ui-link-inherit"><div class="textScheda"><p style="white-space: normal" class="titleEs">'+eserSingle+'</p></div></a></li>';
if(eserSingle.substring(0,2)=='-R') {
var initial = eserSingle.substring(0,2);
var index = arrayEserCardio.indexOf(initial);
//but index return wrong
}
}
I hope I was clear, I do not know javascript very well.. thanks to all
I would write it like this:
var
arrayEserCardio = "try;find;-Reply;Again;",
var indexEserSplit = arrayEserCardio.split(";"),
eserSingle,
link_markup,
i;
for (var i = 0; i < indexEserSplit.length; i++) {
eserSingle = indexEserSplit[i];
cls = "titleEs";
if (eserSingle.substring(0,2) == '-R') {
cls += " with_min_r";
}
link_markup ='<li id="listCardio2"><a onclick="rowSelectedEserCardio()" href="#" class="ui-link-inherit"><div class="textScheda"><p style="white-space: normal" class="' + cls + '">' + eserSingle + '</p></div></a></li>';
}
It should have been
if (eserSingle.substring(0, 2).equals("-R")) {
}
The == operator compares the object references, not the value of the Strings.