I have a table of images in rows of 10 and I'm trying show the id of each image when I click on it. I've tried many, many different ways of this (code below) but no joy. Hopefully someone can set me straight. No point in any jquery or other clever stuff though - I don't understand it yet. Just some simple pointers would help a lot.
document.writeln('<table border = 1 >');
for (var j = 0; j < myArray.length; j++){
if (j % 10 == 0 && j !== 0){
document.writeln('</tr><tr>');
}
document.writeln('<td ><img id = "' + myArray[j].id + '" src="' + myArray[j].src + '" onclick = selectImage() /></td>');
}
document.writeln('</tr></table>');
function selectImage() {
alert(document.getElementById(id));
}
You need add a parameter to selectImage method, so we can send some information to those method. As you can see on my snippet:
var myArray = [
{
id: "id01",
src: "src01.jpg"
},
{
id: "id02",
src: "src02.jpg"
},
{
id: "id03",
src: "src03.jpg"
},
];
document.writeln('<table border = 1 >');
for (var j = 0; j < myArray.length; j++){
if (j % 10 == 0 && j !== 0){
document.writeln('</tr><tr>');
}
document.writeln('<td ><img id = "' + myArray[j].id + '" src="' + myArray[j].src + '" onclick = selectImage(this) /></td>');
}
document.writeln('</tr></table>');
function selectImage(a) {
console.log(a.getAttribute('src'));
console.log(a.getAttribute('id'));
}
when making a call to selectImage, try passing the current image element by using the 'this' keyword i.e selectImage(this)
and then in the script, you can receive the passed object and retrieve the id attribute from there.
function selectImage(obj)
{
alert(obj.id);
}
Related
I have an application using firebase which looks like this:
The tick boxes to the right hand side of each 'Book', when clicked, sends the value of the firebase object into a string as shown below:
When clicking these tick boxes, I would like the style of the box and content to change so they turn blue. I have added this piece of code into the on click event:
function select(data, book, key) {
//What I added
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
//
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
However, this only turns the first box blue. No matter which check box I click, the first one just changes to blue and the rest stay grey.
Here is the JS code which creates the checkbox icons and the JS to highlight the selected check boxes.
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';
//This generates the 3 columns on the application page
for (var i = 0; i < 10 && i < list.length; i++) {
lis += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 10; i < 20 && i < list.length; i++) {
lis2 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 20; i < 30 && i < list.length; i++) {
lis3 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
document.getElementById('bookList').innerHTML = lis;
document.getElementById('bookList2').innerHTML = lis2;
document.getElementById('bookList3').innerHTML = lis3;
};
//This creates the 3 icons of delete, clear and select.
function genLinks(key, bkName) {
var links = '';
links += '<i id="deleteBook" class="material-icons">delete</i> ';
links += '<i id="removeBook" class="material-icons">clear</i> ';
links += '<i id="selectBook" onclick="functionSelected()" class="material-icons">check</i>';
return links;
};
function del(key, bkName) {
var deleteBookRef = buildEndPoint(key);
deleteBookRef.remove();
}
//This is the function to select and insert the data into the string as well as highlight each checkbox
function select(data, book, key) {
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
function buildEndPoint (key) {
return new Firebase('https://project04-167712.firebaseio.com/books/' + key);
}
bookList.on("value", function(snapshot) {
var data = snapshot.val();
var list = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
book = data[key].book ? data[key].book : '';
if (book.trim().length > 0) {
list.push({
book: book,
key: key
})
}
}
}
refreshUI(list);
});
If anybody can help it will be much appreciated.
Thanks,
G
The only thing I can see is that you are using the same id tags for multiple different objects on the same page. If you use it at more than one place, use a class! You should never have more than one of the same id because you will be facing a lot of repeating problems..
I've been stuck with this for several days and I can't solve it.
I've done it with jQuery with no problem, but I need it in pure JS.
This is how my list is generated.
function get_friends(items){
if(items != undefined){
if (items.length != 0){
var html_friends_list = "";
for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);
html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";
}
}
document.getElementById("friends-list").innerHTML = html_friends_list;
As a said I want to save the value of the text and the id of any li element clicked.
Regards
you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.
var list = document.querySelectorAll('li');
Array.prototype.slice.call(list).forEach(function(listItem){
listItem.addEventListener('click', function(e){
console.log(this.id);
console.log(this.innerHTML);
});
});
Here's a JSFiddle which I think demonstrates what you are trying to achieve.
Jsfiddle
Combination of james' answer and working example.
function get_friends(items) {
if (items != undefined) {
if (items.length != 0) {
var html_friends_list = "<ul>";
for (var count = 0; count < items.length; count++) {
if (items[count].subscription == "both") {
html_friends_list = html_friends_list + "<li id='open_chat-" + items[count].jid + "'>"+ items[count].display_name +"</li>";
}
}
html_friends_list = html_friends_list + '</ul>'
document.getElementById("friends-list").innerHTML = html_friends_list;
}
}
}
Note: you should trigger prototype after your dom element created.
I'm using lightGallery and I'm using dynamic creation of galleries, this is the code to generate just one image:
$(this).lightGallery({
dynamic:true,
dynamicEl: [{
'src':'css/images/pictures/gal_'+id+'/1.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/1.jpg'
}]
});
This id variable is always the same, but I want to loop through a number which I take for example from variable x. So, if x=4 the code generated would look like this:
$(this).lightGallery({
dynamic:true,
dynamicEl: [{
'src':'css/images/pictures/gal_'+id+'/1.jpg', //here's 1
'thumb':'css/images/thumbnails/gal_'+id+'/1.jpg'
},{
'src':'css/images/pictures/gal_'+id+'/2.jpg', //here's 2 and so on
'thumb':'css/images/thumbnails/gal_'+id+'/2.jpg'
},{
'src':'css/images/pictures/gal_'+id+'/3.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/3.jpg'
},{
'src':'css/images/pictures/gal_'+id+'/4.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/4.jpg'
}]
});
So I guess the question is how to include a for loop inside an object, if that's even possible, thanks in advance!
No. It's not possible to have control structures(like loops) inside an object definition. You need to create your array of images first, like this:
var dynamicEl = [];
for (var i = 1; i <= 4; i++) {
dynamicEl.push({
'src':'css/images/pictures/gal_' + id + '/'+ i + '.jpg',
'thumb':'css/images/thumbnails/gal_' + id + '/' + i + '.jpg'
});
}
And then to pass it onto the object definition:
$(this).lightGallery({
dynamic:true,
dynamicEl: dynamicEl
});
first create a method to dynamically generate thumbs
function genThumbs(count, id)
{
var arr = [];
for ( var counter = 1; counter <= count; counter++)
{
arr.push( {
'src':'css/images/pictures/gal_'+id+'/' + counter + '.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/' + counter + '.jpg'
} );
}
return arr;
}
then use the same while calling the gallery
$(this).lightGallery({
dynamic:true,
dynamicEl: genThumbs(5, id)
});
Try this
var genEls = function(id, count)
{
var els = [];
for(i = 1; i <= count; i++)
{
els.push({
'src':'css/images/pictures/gal_'+ id + '/' + i + '.jpg',
'thumb':'css/images/thumbnails/gal_' + id + '/' + i + '.jpg',
});
}
return els;
}
var id = 3;
var count = 4;
$(this).lightGallery({
dynamic:true,
dynamicEl: genEls(id,count);
});
This is as inline as it can get ;)
Hope this helps ...
I wanna create such a field with JS and Jquery.
This will enable you make id for every field. Thus you will be able to reference each field by id:
function drawSpace(x) {
for ( var j = 0; j< x; j++) {
for ( var i=0; i< x; i++) {
$('#spacediv').append('<img src="Weltall_Feld.jpg" alt="WeltallFeld" id="field' + i + '_' + j + '"/>');
}
$('#spacediv').append('<br />');
}
}
<div id="spacediv"></div>
I am trying to loop out a JSON object using Javascript (jQuery).
Each object in the array of the main JSON object got embedded arrays containing tags.
I want to loop trough all files in the main object and at the same time loop through the tags and output them together with the files. The object are parsed before looping.
This is the JSON object:
{
"result": [
{
"id": "4f26f21f09ab66c103000sd00e",
"file_url": "http://thefilesat.s3.amazonaws.com/81/0000/12.jpg",
"tags": [
"image",
"elephants"
]
},
{
"id": "4f2422c509ab668472000005",
"file_url": "http://thefilesat.s3.amazonaws.com/9d/0000/7.jpg",
"tags": [
"image",
"green",
"tree"
]
}
]
}
It tried this code but it does not work:
for (var i=0; i < parsed.result.length; i++) {
for (var j=0; j < parsed.result[i].tags.length; j++) {
tags = '<div class="tag">' + parsed.result[j].tags[j] + '</div>';
};
html = '<div class="file""><img src="' + parsed.result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
$("#files").append(html);
};
Your problem is that inside the tags loop, you're using the = operator; which is overwriting the variable your assigning to in each iteration.
Instead, try something like this;
var html = '';
for (var i = 0; i < parsed.result.length; i++) {
var tags = '';
for (var j = 0; j < parsed.result[i].tags.length; j++) {
tags += '<div class="tag">' + parsed.result[i].tags[j] + '</div>';
};
html += '<div class="file""><img src="' + parsed.result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
};
$("#files").append(html);
You also had parsed.result[j].tags[j] rather than parsed.result[i].tags[j].
I've also pulled the appending to $('#files') to be outside the loop so it only happens once, to reduce the amount of DOM lookups and DOM manipulation (as this is slow (in relative terms)).
With:
parsed.result[j].tags[j]
I think you meant:
parsed.result[i].tags[j]
Also, tags = should be tags +=, or you'll just overwrite the previous tag.
You have a typo, the 3rd line must be:
tags = '<div class="tag">' + parsed.result[i].tags[j] + '</div>';
(use result[i] rather than j)
When you're handling objects and arrays it's very cheap to store an extra reference to the array:
var result = parsed.result; // new
for (var i=0; i < result.length; i++) {
var tags = result[i].tags; // new
for (var j = 0; j < tags.length; j++) {
tags += '<div class="tag">' + tags[j] + '</div>';
}
html = '<div class="file""><img src="' + result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
$("#files").append(html);
};
at which point the fact that you inadvertently included the index i twice in your innermost dereference becomes impossible.
This actually performs better too, since the interpreter doesn't have to repeatedly dereference the entire chain of properties over and over.
FWIW, a cleaner jQuery way of writing this without using the .html() method would be:
var result = parsed.result; // new
for (var i=0; i < result.length; i++) {
var div = $('<div>', {'class': 'file'})
.append('<img>', {src: result[i].file_url });
var tags = result[i].tags; // new
for (var j = 0; j < tags.length; j++) {
$('<div>', {'class': 'tag', text: tags[j]}).appendTo(div);
}
$("#files").append(div);
};
which avoids all of the string concatenation, and quote mark escaping, and ensures that any HTML special characters in your tags are correctly escaped, etc.