how to display image through XML to html - javascript

Hie i am practicing XML , Javascript. I want to display image for each animal in a row. But my main problem arises uneven nesting in images . Some have two images while some have 4. I have XML File as follows:
<zoo>
<animal>
<common_name>Elephant</common_name>
<images>
<image>elephant13.jpg</image>
</images>
</animal>
<animal>
<common_name>Emu</common_name>
<images>
<image>emu12.jpg</image>
<image>emu26.jpg</image>
<image>emu23.jpg</image>
</images>
</animal>
<animal>
<common_name>Lion</common_name>
<images>
<image>lion51.jpg</image>
<image>lion46.jpg</image>
</images>
</animal>
<zoo>`
My javascript for img is :
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
images.src ="images/" + zooRoot.getElementsByTagName("image")[i].firstChild.nodeValue;
ul.appendChild(images);
}
}

Try this. This get's the document node of xml and queries for images from it. Once you have the array, you iterate over it and get the inner text from the node.
var xmlimages = xml.getElementsByTagName('image');
for(var i=0; i< xmlimages.length; i++) {
images.src = "images/" + xmlimages[i].innerHTML.trim(); // trim used to remove all the white space from text that you get when you use innerHTML
}

Please insert loop on node:
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
var imgData = zooRoot.getElementsByTagName("image");
for (i = 0; i <imgData.length; i++) {
images.src ="images/" + imgData[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
}

Try to get Animal as an object, then create a HTMLstring and insert it in node;
var animalsNode = zooRoot.getElementsByTagName('animal');
var animals = [];
for(var i=0; i<animalsNode.length; i++){
var animalName = animalsNode[i].getElementsByTagName("common_name").innerHTML;
var animalImageNodes = animalsNode[i].getElementsByTagName("image");
var animalImages = [];
//will store image paths into animalImages
for(var j=0; j<animalImageNodes.length; j++){
animalImages.push("image/" + animalImageNodes.innerHTML);
}
animals.push({
common_name: animalName,
images: animalImages //array of image urls
})
}
var animalsHTML = function(animals){
//lets cereate string with "html table"
var animalsHtml = "<table>";
for(var i=0; i<animals.length; i++){
animalsHtml += "<tr>";
animalsHtml += "<td>" + animals[i].name + "</td>"
+ "<td><img src='" + animals[i].images[0] + "' /></td>";
animalsHtml += "</tr>";
}
animalsHtml += "</table>";
return animalsHtml;
}
tableNode.innerHTML = animalsHTML(animals);
or you can define animal array more functional way =)
var animals = zooRoot.getElementsByTagName('animal').map(function(animalNode){
return {
common_name: animalNode.getElementsByTagName('common_name')[0].innerHTML,
images: animalNode.getElementsByTagName('image').map(function(imageNode){
return "image/" + imageNode.innerHTML;
})
};
});
//and more js style of draw-function
var animalsHTML = function(animals){
return "<table>" + animals.reduce(function(curr, next){
return curr + "<tr><td>" + next.name + "</td>"
+ "<td>"
+ next.images.reduce(function(c, n){
return c + "<img src='" + n "' />"
},'')
+ "</td>"
+ "</tr>";
}, '') + "</table>";
}
tableNode.innerHTML = animalsHTML(animals);
I didn't test it, but it should work.

Related

How to display selected file names before uploading multiple files in javascript

How to use table instead of list for alignment. Also ones we click the cancel button the file list need to be deleted from list.
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
output.innerHTML = '<ul style="list-style-type:none">';
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '<li>' + input.files.item(i).name + ' <button>X</button></li> ';
}
output image for the above code
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i)
{
HTML += "<tr><td>" + input.files.item(i).name + "</td><td> <button>X</button></td></tr>";
}
HTML += "</table>";
output.innerHTML = HTML;
}

How do I apply code to a dynamically created element

The following code works only if the table is already present in the document upon page load. I however want it to apply on a dynamically created table.
Can this be done?
var colNumber=22
for (var i=0; i<colNumber; i++)
{
var thWidth=$("#tbl").find("th:eq("+i+")").width();
var tdWidth=$("#tbl").find("td:eq("+i+")").width();
if (thWidth<tdWidth)
$("#tbl").find("th:eq("+i+")").width(tdWidth);
else
$("#tbl").find("td:eq("+i+")").width(thWidth);
}
The table is created in the following way:
function loadFile(event){
alasql('SELECT * FROM FILE(?,{headers:false})',[event],function(data){
var keys = [];
for (var i = 0; i < data.length; i++) {
for (var categoryid in data[i]) {
var category = data[i][categoryid];
keys.push(categoryid);
}
}
keysConverted = keys.map(foo);
var vMin = Math.min.apply(null, keysConverted);
var vMax = Math.max.apply(null, keysConverted);
var start = vMin-1
var ColNeeded = vMax - vMin+1;
var arrExcel2Table = '<table id="tbl">';
for (var i = 0; i < data.length; i++){
arrExcel2Table = arrExcel2Table + '<tr>';
for (var j = 0; j < ColNeeded; j++){
cellValue = data[i][number2Letter(j+start)];
if (typeof cellValue === "undefined"){
cellValue = '';
}
arrExcel2Table = arrExcel2Table + '<td>' + cellValue + '</td>';
}
arrExcel2Table = arrExcel2Table + '</tr>';
}
arrExcel2Table = arrExcel2Table + '</table>';
document.getElementById('excel_table').innerHTML = arrExcel2Table;
});
}
Create a function you want to run and add an event from the dynamic element. For example
arrExcel2Table = arrExcel2Table + '<td>' + cellValue + '</td>';
can be replaced by
arrExcel2Table = arrExcel2Table + '<td onclick="myFunction();">' + cellValue + '</td>';
Above code will call the function you created
myFunction() {
alert();
}
Just create your table, then apply whatever code you want to it :
$('#excel_table').html(arrExcel2Table);
adjustWidth()
function adjustWidth(){
var $tbl = $("#tbl"); // And cache your jQuery objects!! Massive performance boost
for (var i=0; i<colNumber; i++)
{
var $th = $tbl.find("th:eq("+i+")"),
$td = $tbl.find("td:eq("+i+")"),
thWidth = $th.width(),
tdWidth = $td.width();
if (thWidth<tdWidth)
$th.width(tdWidth);
else
$td.width(thWidth);
}
}

Only show objects in array that contain a specific string

I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>

Pure Js onclick element doesn't work

I'm having trouble when i run this code under greasemonkey the last position working and run function.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML = document.getElementById('moje_menu').innerHTML + '<p id="' + arry[i] + '">' + arry[i] + '</p>';
document.getElementById(arry[i]).onclick = delete;
}
On 10 position the last working ... WHY ????
When you replace the innerHTML you remove all previous event handlers.
In plain JS you can detect the click in the div but you need to check the event:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
window.onload=function() {
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '">' + arry[i] + '</p>';
}
document.getElementById('moje_menu').onclick=function(e) {
var event = e?e:window.event,tgt = event.target || event.srcElement;
if (tgt.tagName.toLowerCase()=="p") {
console.log(tgt.id);
}
}
}
<div id="moje_menu"></div>
Alternative is inline since you generate the P anyway
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="delete(this)">' + arry[i] + '</p>';
}
You can the modify delete (poor name for a function since delete is a built-in method) to handle the passed paragraph
Example:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="removeP(this)">' + arry[i] + '</p>';
}
<div id="moje_menu"></div>
In jQuery you can easily delegate:
function removeP() {
console.log(this.id);
}
$(function() {
var arry = ["a","b","c"];
var $menu = $('#moje_menu');
for (var i=0; i<arry.length; i++) {
$menu.append($('<p/>',{"id":arry[i], "text":arry[i]}))
}
$menu.on("click","p",removeP);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="moje_menu"></div>
This is my solution i dont like them but works.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i<arry.length; i++) {
// if(arry[i].search('player')==''){
document.getElementById('moje_menu').innerHTML += '<p class="lista_farm" id="'+arry[i]+'">'+arry[i]+'</p>';
//document.getElementById(arry[i]).onclick = usun_farme;
//}
}
var lista_farm = document.getElementsByClassName('lista_farm');
for(var i = 0; i<lista_farm.length; i++){
lista_farm[i].onclick = usun_farme;
}

javascript inline code link generating chrome extension

I'm trying to make an extension for chrome that grabs data from a website and I'm having trouble making the links clickable. I CAN NOT use javascript inside the link (ex: href="javascript:myfunction(param);")
I need to create a div for each title, then create a onclick function that handles the div's innerhtml, and I can't get it to work.
here is my code so far:
document.addEventListener('DOMContentLoaded', function () {
$().ready(function () {
var url = 'http://somewebsite';
$.get(url, function (data) {
data = data.split("<tr name=\"hover\">");
var name;
var link;
var count = data.length;
count++;
for(var i = 1; i < data.length; i++){
data[i] = data[i].replace("<br>","<br />");
data[i] = data[i].replace("class=\"thread_link\"", "");
data[i] = data[i].replace("<td class=\"forum_thread_post\" align=\"center\">0</td>","");
data[i] = data[i].replace("<td class=\"forum_thread_post\">","");
data[i] = data[i].replace("</td>","");
data[i] = data[i].replace('<td class="forum_thread_post" align="center">0</td>','');
if(i != data.length-1){
data[i] = data[i].replace("<a href=\"", "");
data[i] = data[i].replace("</a>", "");
data[i] = data[i].split("\" >");
data[i][1] = data[i][1].split("<");
document.write('<div id="' + data[i][1][0] + '">' + data[i][1][0] + data[i][0] + "</div><br /><br />");
}else{
data[i] = data[i].split("</table>")[0];
data[i] = data[i].replace("<a href=\"", "");
data[i] = data[i].replace("</a>", "");
data[i] = data[i].split("\" >");
data[i][1] = data[i][1].split("<");
document.write('<div id="' + data[i][1][0] + '">' + data[i][1][0] + data[i][0] + "</div>");
}
}
//document.body.innerHTML = '';
//console.log(data);
});
});
});
document.write('</script>');
function getshow(url){
alert(url);
document.body.innerHTML = '';
$.get("http://somewebsite" + url, function (dat) {
document.write(dat);
});
}

Categories