Hi i am doing an application in phonegap,in that application i need to show list of the users in the listview contains profile pic,name,number and online status .
for (var i = 0; i < roster_items.length; i++) {
var jid_contact=roster_items[i].getAttribute('jid');
var name_contact=roster_items[i].getAttribute('name');
/// Add all the contacts to Array
$('#contacts-listview').append(
'<a href="#" onclick="user_contactsClicked('+ i + ');">' +
'</br>'+
'<div id="contact_img">'+
'<img id="splash" src="images/contact_default_pic.png" />'+
'<ul id="menu">'+'<li id="contact">'+name_contact+'</li>'+
'<li id="status">'+jid_contact+'</li>'+'</ul>'+
'<div class="pull-right"><div><img id=i class="status_img" src="images/user_online.png" /></div>'+
'<div style="margin-bottom: 10px;"><ol id="date">'+
'<li>date</li>'+
'<li>time</li>'+
'</ol></div></div>'+
'</div>'+
'</br>'+
'</a>'
);
}
and i will call a function for changing the online status for a particular user and changes the image
changeOnlineStatus_contact : function(elementPos) {
alert(elementPos);
if(elementPos>=0) {
//Get current table
document.getElementById(i).src = "images/user_offline.png";
}
}
for this i want to give if for the img element dynamically. Please suggest me.
Thanks in advance..
The reason the id isn't getting set on the image is because you've got:
"…<img id=i class=…" which means that every image has the id of "i"
If you changed this to:
"…<img id=\""+i+"\" class=…" then it would use the value of i as the id attribute
If you have more complex bindings to the UI, I'd recommend looking at something like http://knockoutjs.com/ - this way you would update the underlying model, and the html would automatically be updated to represent it.
Related
I'm using javascript to add html to my 's.
I made a loop that goes around all projects there are. There are multiple projects and in every project there are multiple pictures.
The first part creates the first projecttitle within a div that gets an id(the projectname) and the first pictures.
$( ".projectbeeldcontainer" ).append(
'</div>'+
'<h1 class="projecttitel" id="'+name+'">'+name+'</h1>'+
'<div class="row dashboardrow" id="'+name+'id">'+
'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>';
);
After this, the script will check if the projectname of the next image allready exists. If it does exist (because we added it with the code above), then it will insert a new div inside of the project div we created:
document.getElementById(name+'id').append(
'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>'
);
The problem i have now is that the first line of code successfull creates the div's and the image. The second code works for 98%.
It does recognise the div with the id and puts the content in it. But the problem is that it adds quotes before my first line and after. So it looks like it thinks it's a string and not html.
So it literally adds "<div ..." on my page.
Can anyone help me please? Sorry for the bad spelling and grammar.
Use innerHTML instead of append.
document.getElementById(name+'id').innerHTML += "<div> put your html </div>";
Append adds a textNode. Better way is something like this by generating it and inserting into the DOM:
var el = document.createElement("div");
el.appendChild(document.createTextNode("Put yout HTML"));
document.getElementById(name+'id').appendChild(el);
The problem is that you are literally telling it to append a string to the DOM, you are not creating an element that you can insert.
If you wrap the html that you are trying to append in the jQuery wrapper $('<div class="col-sm-2">....</div>');, then it will be treated by jQuery as an a jQuery object and should then be able to be inserted in the manor that you need.
This work to me
var stringToHTML = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};
$( ".projectbeeldcontainer" ).append(stringToHTML('<p>text</p>'))
DEMO
var insertData = '<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>';
document.getElementById('a').innerHTML = insertData;
<div id="a"></div>
You can just use < and > instead of "<" and ">" in your code. Browser will not recognize this string as html code and print it as a plain text.
I've used the code posted in THIS STACKOVERFLOW POST to build a prototype of a webbapp, but I can't make the second page show me the data with the format I want.
The code shows me the second page with all the data in a grid format, but I want to know how to make specific data with different formats (bold, italic, color).
For example, one string that I use is a "image.jpg" text to load an image of the user.
I've modified the first part of the code to:
$.each(info, function (i, valor) {
li += '<li><img src="img/'+ valor.foto +'"><h2><i>' + valor.cientifico + '</i></h2><p><b>Familia:</b> <i>'+ valor.familia +'</i> | <b>Subfamilia:</b> <i>'+ valor.subfamilia +'</i></p></li>';
});
to add specific values and apply different format (familia, subfamilia) and to insert the picture with the "foto" value.
Then the code continues:
$("#lista").append(li).promise().done(function () {
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
$("#resultado").data("info", info[this.id]);
$.mobile.changePage("#resultado");
});
$(this).listview("refresh");
});
});
$(document).on("pagebeforeshow", "#resultado", function () {
var info = $(this).data("info");
var info_view = "";
for (var key in info) {
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
$(this).find("[data-role=content]").html(info_view);
});
I know that the for (var key in info) is not what I'm looking for, but I don't know what code I have to use because I'm too new to unsderstand how to do it. How can I accomplish this?
The code next to info_view is HTML, right, but if I replace + key + with + familia + for example this doesnt works like before.
My question is how can I make to retrieve an specific data (for example the foto value) of the selected item listed in the first page? I want to be able to select wich items use. For example, I wanna make the id value invisible for the user, make the id value invisible, the name value in bold, and so on
Hope I was enough clear, sorry for my limited english and coding knowledge
Finnaly I've solved my own question.
For reference, what I do was deleted the
for (var key in info) {
and inside the info_view += part i've used info['value'] for each item I want to manipulate.
Hope this helps someone else.
I have this javascript code where it goes for each movies in jsonp dataType. For each movies I have to display its thumbnail image and its title together with the star rating. To display the star symbols below for each movies I have this code:
var include = '<div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>';
$(".prediction").html(include); //DISPLAYS THE PREDICTION RATING
It simply sets the html content of the class prediction to this -> <div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>
I tried to use this on directly on my html code and it is fully working I can see the stars. Here it is:
But I tried this on javascript and it is not displaying. I just want to have ratings below for each and every movies.
This is my javascript code:
var html = '';
var count = 0;
$.each(data.movies, function(index, movie) {
html += '<div class="item col-xs-6 col-md-3">';
html += '<div class="thumbnail" style="min-height:320px;max-height:320px;">';
//add link here
html += '<a href="viewMovieDetails.php?id=' + movie.id + '">'
html += '<img src="' + movie.posters.detailed + '" style="width:175px; height: 230px;" class="img-responsive" alt="" ></a>';
html += '<div class="caption">';
html += '<h5>' + movie.title + '</h5>';
html += '<div class="prediction"></div>';
html += '</div></div></div>';
//set a delay (1second) for a call on rotten tomatoes api and
//store data on db
if(count > 5){
setTimeout(function() { storeDataOnDB(movie.id);; }, 1000);
count = 0;
}
else{
count++;
}
});
// Append movies
$('#movie_recommend').html(html);
var include = '<div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>';
$(".prediction").html(include); //DISPLAYS THE PREDICTION RATING
What do you think is wrong? Am I missing something? or is there other way to do it. Thanks for the help.
You should notify RateIt plugin, that new data is available, just add this:
$(".rateit").rateit();
after $(".prediction").html(include);
Is there a better way of inserting somewhat complex html into a page other than the way I'm doing now? :
function display(friends) {
$(".row").empty();
$.each(friends, function(index, friend) {
var html = '<div class="profileImage" style="float:left;padding:20px; width:200px">';
html += '<a href="/app/click/' + friend.id + '">';
html += '<img id="' + friend.id + ' " src="https://graph.facebook.com/' + friend.id + '/picture?width=200&height=200 " />';
html += '</a>';
html += '</div>';
$(".row").append(html);
});
Currently I have a list of facebook friends which are styled nicely. When a user searches through the friends, the entire content block is emptied and the result is appended (i'm using autocomplete). However the design could change and get more complex so i'm looking for a scalable way of doing what I have above.
Instead of creating the html inside the javascript, is there a smarter way of doing this? Perhaps with $.load() and passing each friend as an argument? But that seems very slow and server intensive if you have to list 100 friends.
One good way to go would be to use a templating engine, handlebars (as mentioned in the prev answer) is one of them. You could create your own as well if your scenario is simple as this. And another key thing is not to use append inside the loop, instead construct them to a temp array and add it to the DOM in the end. If your list is big and appending to the dom in the array can be expensive.
Add the template html with a placeholder for friendId
<script type="text/html" id="template">
<div class = "profileImage" style = "float:left;padding:20px; width:200px">
<a href = "/app/click/{{friendId}}">
<img id = "{{friendId}}" src = "https://graph.facebook.com/{{friendId}}/picture?width=200&height=200 " />
</a>
</div>
</script>
And
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = [];
$.each(friends, function (index, friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
rows.push(templateHtml);
});
$row.html(rows); //Append them in the end
}
Demo
You could use $.map as well.
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = $.map(friends, function (friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
return templateHtml;
});
$row.html(rows);
}
A scalable solution would be to use a template engine and make the server returns JSON response.
Take a look at Handlebars.js http://handlebarsjs.com/
Am creating a comment system for a web app, the comments are loaded when a user clicks on the comment image, html code is dynamically generated with json to display the comments.
But when the image is clicked again,the request is made again populate the page with the same data
Heres my code
function latest_pheeds() {
var action = url+"pheeds/latest_pheeds";
$.getJSON(action,function(data) {
$.each(data,function(index,item) {
$('#pheed-stream').append
(
'<div class="pheed" id="'+item.pheed_id+'">'+
'<p>'+item.user_id+'</p>'+
'<p>'+item.pheed+'</p>'+
'<div class="pheed_meta">'+
'<span>'+item.datetime+' Ago</span>'+
'<span>'+item.comments+
'<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
'</span>'+
'</div>'+
'</div>'
);
});
});
}
function retrieve_comments(pheed_id) {
var action = url+'comments/get_comments';
var crsf = $('input[name=ci_csrf_token]').val();
var dataString = "pheed_id="+pheed_id+"&ci_csrf_token="+crsf;
$.ajax({
url:action,
type:'POST',
cache:false,
dataType:'json',
data:dataString,
success:function(data) {
$.each(data,function(index,item) {
$("#" + pheed_id).append(
'<div class="pheed_comments">'+
'<div class="comment">'
+'<span><p>'+item.user+'</p></span>'
+item.comment+
'</div>'+
'</div>'+
'<div id="comment_box">'+
'<textarea id="comment" cols="30">'+
'</textarea><br>'+
'<input type="button" class="submit_btn" value="comment" />'+
'</div>'
);
});
}
});
}
latest_pheeds() loads the pheeds and retrieve_comments gets the comments of the pheed_id passed to it.
How do i determine if the comment area has already been populated and instead update it with new comments if available. Thanks
Check for
$("#" + pheed_id +' .pheed_comments').length
if will be 0 if the element(I guess vou mean div.pheed_comments ) doesn't exist.
Several choices:
1) If you already have all the comments from your ajax call, then just remove the previous comments you have from the DOM and insert everything you just got.
2) If you have an ajax call that can retrieve just the new comments, then you can just check the DOM to see if you already have comments in the DOM and then just request new comments after some token in time (that you would have previously saved). When you receive the new comments, you would append them to what you have.
$('#pheed-stream').children().length will tell you how many children there are in the pheed-stream hierarchy. If that's zero, you haven't done any pheeds yet.
I would suggest that it's probably easiest to just retrieve all the comments and replace everything you have with the new list of comments than to try to retrieve just the new comments. Retrieving just the new comments will require some sort of time token that you can give the server so it knows which "new comments" to give you.
$("#" + pheed_id + " .pheed_comments").length will tell you whether any comments have been retrieved yet for that pheed_id.
you are adding div with id. Just check if it exists. If yes, then update it, otherwise insert.