replace image name from array - javascript

I have a page that displays 6 rows containig 3 images each. Each image is enlarged onmouseover. The page is showing a list of "events" thefore it will grow in the future and and each new event will be the first of the list.
I think that it would be more practical if I could replace the names of the images with generic ones (image1,image1_small...) and have an array that assigns the right names to the images.
something like this:
var imm1 = "ragaini2016_small.jpg";
var imm2 = "ragaini2016.jpg";
var imm3 = "possenti2016_small.jpg";
var imm4 = "possenti2016.jpg";
......
But I don't know how to write the code inside the <img src="xxx" ....
Here below the html code of one of the rows:
<div class="row" style="margin-left:auto;margin-right:auto; width=100%">
<div class="col-md-4" style="background-color:transparent;padding-top:1%;" >
<p style="background-color:transparent;text-align:center;color:white;font-weight:bold;">7 Maggio 2016</p>
<div class="ienlarger" style="margin: 0 auto; display:table;" >
21 Aprile 2016
19 Marzo 2016
thank you
gabriele

Here is a small snippet to add an array of images to HTML. I'm pretty sure this isn't exactly what you need, but here's a start.
let arr = ['image1.jpg', 'image2.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg'],
imageTags = [], divElt = document.getElementById('ienlarger');
arr.forEach(function(item, index) {
img = document.createElement("img");
img.src = item;
divElt.appendChild(img);
});
<div class="row" style="margin-left:auto;margin-right:auto; width=100%">
<div class="col-md-4" style="background-color:transparent;padding-top:1%;">
<p style="background-color:transparent;text-align:center;color:white;font-weight:bold;">7 Maggio 2016</p>
<div id="ienlarger" class="ienlarger" style="margin: 0 auto; display:table;"></div>
</div>
</div>

Here are the required steps:
Create a container html div element and give an id to it, lets say id="container".
Create the array of image name in javascript. (an array not a variable)
var image_array = {"ragaini2016_small.jpg", "ragaini2016.jpg", ..... so on};
In the javascript, write a for loop. In the loop, write the code for the table row.
var table_content = "";
for(var i=0; i<=3; i++) {
table_content = '<img src = "' + image_array[i] + '" />'
}
image_array[i] will replace the image name from the array to the content in the loop.
Assign the "table_content" to the innerHTML of the container.
document.getElementById("container").innerHTML = table_content;

Related

How can I add the same XML tags multiple times, with different content?

I have some problems with my code. I want to create an XML Document with JQuery / JavaScript. I am now at the point, where I want to create a few Tags and populate them each with the same tags but different content inside the tags.
Here is the code for better understand
function setItems(xmlDoc, channelTag){
const itemList = [];
const itemTitle = xmlDoc.createElement("title");
const itemLink = xmlDoc.createElement("link");
const itemGuid = xmlDoc.createElement("guid");
const itemMediaContent = xmlDoc.createElement("media:content");
const itemMediaDescription = xmlDoc.createElement("media:description");
itemList.push(itemTitle, itemLink, itemGuid, itemMediaContent, itemMediaDescription);
for (var i = 0; i < jsonObj.length; i++){
var item = xmlDoc.createElement("item");
channelTag.appendChild(item);
//Populate the <item> with the tags from "itemList" and content from "jsonObj"
$.each(itemList, function(index) {
$(channelTag).children('item')[i].appendChild(itemList[index]).textContent = jsonObj[0].title;
})
}
}
The Output of the code looks like this:
<item></item>
<item></item>
<item>
<title>Something</title>
<guid>Something</guid>
<link>Something</link>
<media:content>Something</media:description>
<media:description>Something</media:description>
</item>
It always populates the last item-Tag but not the ones above. What I want is that every item-Tag has the same child-Tags (e.g. title, link, guid and so on). Is there something i am missing some unique tags or something like that?
Edited:
Here is some minimal HTML and XML. The values for the function "xmlDoc" and "channelTag" just contains some Document Elements, where my items should be appended, like so:
<rss>
<channel>
<title>SomeTitle</title>
<atom:link href="Link" rel="self" type="application/rss+xml"/>
<link>SomeLink</link>
<description>SomeDesc</description>
<item></item>
<item></item>
<item></item>
</channel>
</rss>
<div class="col-5 col-sm-5 col-lg-3 order-2 count">
<a class="guid1"><img class="card-img image1"></a>
</div>
<div class="col-7 col-sm-7 col-lg-5 order-2">
<div class="card-body">
<a class="guid1">
<h5 class="card-title title1 overflow-title"></h5>
</a>
<p class="card-text body1 text-body overflow-body"></p>
<div class="card-body subtitle">
</div>
</div>
</div>
There are several issues with your code but the area we mostly want to focus on is this:
for (var i = 0; i < jsonObj.length; i++){
var item = xmlDoc.createElement("item");
channelTag.appendChild(item); // you're adding a node here
$.each(itemList, function(index) {
$(channelTag).children('item')[i].appendChild(... // and here
})
}
Instead of appending nodes multiple times per iteration, you should create and populate your node before add it it to channelTag.
Here's a way your could do it:
// use a "$" sign as a variable name prefix, so you know it's a Document Element and not a regular javascript variable
var $item = xmlDoc.createElement("item");
// you don't need jQuery for this iteration
itemList.forEach(function (item, index) {
$item.appendChild(itemList[index]).textContent = jsonObj[0].title;
});
// if "channelTag" is a Document Element, rename it "$channelTag"
$channelTag.appendChild(item);
Couple things about the code above:
you don't need jQuery, use forEach instead
there is no way telling what type is channelTag. If it is a selector (of type string), use $(selector), but you are using the appendChild() method before, suggesting it's actually a Document Element. In that case you don't need to wrap it with $()
I don't have the context needed to test this code, so no guarantee it'll work out of the box. But try and re-read your code and go through it top-to-bottom. For each variable, describe its type and value. I found that to be helpful when I'm lost in code.

Combine divs within a for loop

Is it possible to use a JavaScript for loop to combine a number of div's? I have 16 sets of these I am wanting to put into a for loop. The problem I am having is that its HTML not JavaScript I am trying to do this with. I haven't seen anything so far on how to go about this. Thanks for any help or suggestions.
What the following code does is catch the data pre-defined from a 16X17 table and inserts it into one cell in my document. I then have have other code using the div id's that makes visible just the one I need.
<div id="101" class="hidden"><script>document.write(tab1a1)</script></div>
<div id="102" class="hidden"><script>document.write(tab1a2)</script></div>
<div id="103" class="hidden"><script>document.write(tab1a3)</script></div>
<div id="104" class="hidden"><script>document.write(tab1a4)</script></div>
<div id="105" class="hidden"><script>document.write(tab1a5)</script></div>
<div id="106" class="hidden"><script>document.write(tab1a6)</script></div>
<div id="107" class="hidden"><script>document.write(tab1a7)</script></div>
<div id="108" class="hidden"><script>document.write(tab1a8)</script></div>
<div id="109" class="hidden"><script>document.write(tab1a9)</script></div>
<div id="110" class="hidden"><script>document.write(tab1a10)</script></div>
<div id="111" class="hidden"><script>document.write(tab1a11)</script></div>
<div id="112" class="hidden"><script>document.write(tab1a12)</script></div>
<div id="113" class="hidden"><script>document.write(tab1a13)</script></div>
<div id="114" class="hidden"><script>document.write(tab1a14)</script></div>
<div id="115" class="hidden"><script>document.write(tab1a15)</script></div>
<div id="116" class="hidden"><script>document.write(tab1a16)</script></div>
<div id="117" class="hidden"><script>document.write(tab1a17)</script></div>
Update: Pulling data from table
<!--Start- Takes Assembly number from Data Table--> <!--Change "<Col1;" equala columns-->
for (var x = 1; x<Col1; x++){window["aa"+x] = document.getElementById("part1Table").rows[0].cells[x+1].innerHTML;}
<!--End--- Takes Assembly number from Data Table-->
<!--Start- Takes Assembly Rows from Data Table--> <!--Change "<Row1;" equals rows-->
for (var y = 1; y<Row1+1; y++){window["rows"+y] = document.getElementById("part1Table").rows[y].cells[1].innerHTML;}
<!--End- Takes Assembly Rows from Data Table-->
<!--Start- Takes Part number from Data Table--> <!-- "<Col1;" equals columns----> <!-- If a Column is added to main table add a new line below---->
for (var z1 = 1; z1 <Col1; z1++) {window["tab1a"+z1] = document.getElementById("part1Table").rows[1].cells[z1 +1].innerHTML;}
for (var z2 = 1; z2 <Col1; z2++) {window["tab2a"+z2] = document.getElementById("part1Table").rows[2].cells[z2 +1].innerHTML;}
for (var z3 = 1; z3 <Col1; z3++) {window["tab3a"+z3] = document.getElementById("part1Table").rows[3].cells[z3 +1].innerHTML;}
Try using AngularJS (which is a javascript framework that you can easily add to your html page (see AngularJS.com for a quick intro))
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app='myApp'>
<div ng-repeat='entry in entries'>
<div id={{entry.id}} class="hidden"><script>document.write({{entry.table}})</script></div>
</div>
<script src='app.js'></script>
</body>
</html>
Then within a controller in a file called app.js you would make a array of objects 1...100 or whatever number you want and pass it to a scope like this
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', function($scope) {
$scope.entries = [{
id: '101', table: 'tab1a1'}, {id: '102', table: 'tab1a2'}]
// extend to your own range
});
having a bunch of sequential variables like tab1a1 is difficult to work with. Can you put those in an array? Then...
var b=document.getElementsByTagName('body')[0];
for(var i=1; i<18; i++){
var d=document.createElement('div'); //make a div element
d.id='10'+i; //assign sequential id
d.innerHTML=tab1a[i]; //put the the array element content corresponding to that number into the new div element
b.appendChild(d); //place new element into the DOM
}
Another option would be to use excel and basically make a column with on the rows 101,102,103... And a similar same column for the tables. Then just add the code lines in string format and bind the colums together with &. Copy everything and paste this in notepad and then in your code!
Ex:
="<div id='" & A1 & "' etc etc
Thank you to everyone who gave suggestions. I spent a few more hours with the code and came up with the following. It works great in testing. I can now add and remove rows and columns from my table without having to change the code.
for (var w = 1; w <Row1; w++)
for (var z1 = 1; z1 <Col1; z1++) {window["tab" + w + "a" + z1] = document.getElementById("part1Table").rows[w].cells[z1 +1].innerHTML;}
This replaces my 17 lines of the following:
for (var z17 = 1; z17 <Col1; z17++) {window["tab17a"+z17] = document.getElementById("part1Table").rows[17].cells[z17 +1].innerHTML;}
This is very good because my new table has 50+ rows.

Repeat div tags in specific number of sets from angularjs in html code

I have the following div tag which I want to repeat multiple times
<div class="item">
<div class="col-xs-3 " style="margin-right:-50px;" ng-repeat="(key, value) in products.slice(4, 8) track by $index">
<img src= {{value.imageUrl}} alt="No Image"/>
</div>
</div>
I want repeat the above entire div tag multiple times where each div tag displays 4 images at a time i.e the next div tag will have ng-repeat="(key, value) in products.slice(8, 12) track by $index" and so on till there are images in the value object. How can this be achieved using angularjs?
Appreciate your help. Thanks in advance.
I think you should prepare the data better in the controller that's providing the products array. You could probably do this all inline but my guess is it would be pretty nasty.
Here's my suggestion.
The bottom code would provide you with arrays each with four entries of your images. You could change that by modifying the count variable and the reset inide the loop.
ExampleController.js
'use strict';
app.controller('ExampleCtrl', function ($scope) {
var products = [
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'},
{'name':'Test','url':'some_image.jpg'}
];
var products_page = [];
var products_pages = [];
var count = 4;
$scope.products_pages = products_pages;
for(var i=0;i<products.length;i++){
if(count > 1){
products_page.push(products[i]);
count--;
if(products.length === i+1){
products_pages.push(products_page);
return;
}
}else{
products_page.push(products[i]);
products_pages.push(products_page);
products_page = [];
count = 4;
}
}
});
Now with this out of the way you could do the following in the HTML.
<div class="item" ng-repeat="page in products_pages">
<div class="col-xs-3 " style="margin-right:-50px;" ng-repeat="image in page">
<img src= {{image.url}} alt="No Image" />
</div>
</div>
Haven't tested it but I think this should do the trick. If you need it to be all inline, somebody else will have to pitch in.

multidimensional object building in javascript using loops

So i have a html layout in which there are blocks (there are no fix number of them, because they can be created dynamically).
In these blocks there are boxes (again, they can be created dynamically)
The boxes contain *html element*s and also have different data attributes
So i need to create an object which looks like this
block1 = {
box1 : {
id : box1.data('id'),
content : box1.html()
},
box2 : {
id : box2.data('id'),
content : box2.html()
}
},
block2 = {
box3 : {
id : box3.data('id'),
content : box3.html()
}
}
Please don't write that the syntax is not correct, i know. I just tried to somehow illustrate what i want.
So my question is how do i do this with the help of jQuery?
Thank you in advanced
You can select all blocks and boxes and iterate over each of them using .each [docs]:
var blocks = {};
$('.block').each(function(index) {
var boxes = {};
$(this).find('.box').each(function(index) {
boxes['box' + index] = {
id: $(this).data('id');
content: $(this).html();
};
});
blocks['block' + index] = boxes;
});
You might not need an object of objects though, maybe an array of array suffices or would be even better, depending on what you intend to do with the data.
To learn more about how objects work, have a look at MDN - Working with Object.
Here is an idea:
1- Iterate over all of the blocks using some CSS selector.
2- Create a generic JS object and set a collection attribute called "boxes" to be an array
3- For each one, iterate over all the boxes inside it, again, using some CSS selector.
4- Create a generic JS object for each box and set the attributes as needed.
Code version
I think something like this would work (not tested):
var blocks = new Array();
$(".blocks").each(function(b) {
var my_block = {boxes: new Array()};
var $block = $(b);
$(".box", $block).each(function(box) {
var $box = $(box);
my_block.boxes.push({id: $box.attr("id"), content: $box.html()});
});
blocks.push(my_block);
});
You should take a look at Knockout.js, it's very comfortable to build an application like yours.
In detail: use Objects. Build an array for yourself, containing Objects with e.g. Block Name and all Child nodes.
<div id="lanesContainer" data-bind="foreach: blocks">
<div id="" class="dropLane laneDefault ui-widget-header ui-dialog ui-widget ui-corner-all ui-front ui-resizable">
<div class="ui-dialog-titlebar ui-helper-clearfix" data-bind="drop: {value: $data.dropTask}">
<p class="laneheader" data-bind="text: $data.title">Lane</p>
</div>
<ul data-bind="foreach: box">
<li class="ui-dialog-content laneItem" data-bind="drag: {value: $data}">
<div class="ui-widget-header laneItemHeader" data-bind="text: $data.Title"></div>
<div class="ui-widget-content laneItemBody" data-bind="text: $data.Description"></div>
<div class="ui-widget-content laneItemFooter">
<div class="ui-corner-all ui-state-default notification-important">
<span class="ui-icon ui-icon-notice" title="sometitle" data-bind="css: {'notification-important-hide': !$root.isElementImportant($data) }"></span>
</div>
</div>
</li>
</ul>
</div>
</div>
Is this useful?
Here is how to get an Object with nested Array of Childs:
function laneObject(title) {
var obj = new Object();
obj.title = title; //Identifier for Lane
obj.childs = []; //Elements of Lane to display
return obj;
}
I am not entirely sure of what your question is, but if you want to create blocks and boxes dynamically, I suggest you first of all use Arrays.
//All dynamically created blocks
blocks = [];
//Create blocks
for(var i = 1; i < 3; i++) {
var block = {
//All dynamically generated bloxes
boxes = [];
};
//Create boxes
for(var j = 1; j < 4; j++) {
block.box[j] = {
id : j,
content : '<span>html for box' + j + '</span>'
}
}
blocks[i] = block;
}

sorting elements using jquery

I have a div, #containerDiv, which contains elements related to users like first name, last name etc. in separate divs. I need to sort the contents of the container div based on the last name, first name etc. values.
On searching google the examples I got all are appending the sorted results and not changing the entire HTML being displayed. They are also not sorting by specific fields (first name, last name).
So please help me in sorting the entire content of #containerDiv based on specific fields and also displaying it.
The Page looks Like something as mentioned Below:
<div id="containerDiv">
<div id="lName_1">dsaf</div><div id="fName_1">grad</div>
<div id="lName_2">sdaf</div><div id="fName_2">radg</div>
<div id="lName_3">asdf</div><div id="fName_3">drag</div>
<div id="lName_4">fasd</div><div id="fName_4">gard</div>
<div id="lName_5">dasf</div><div id="fName_5">grda</div>
<div id="lName_6">asfd</div><div id="fName_6">drga</div>
</div>
On getting sorted by last name div values, the resulted structure of the container div should look like:
<div id="containerDiv">
<div id="lName_3">asdf</div><div id="fName_3">drag</div>
<div id="lName_6">asfd</div><div id="fName_6">drga</div>
<div id="lName_5">dasf</div><div id="fName_5">grda</div>
<div id="lName_1">dsaf</div><div id="fName_1">grad</div>
<div id="lName_4">fasd</div><div id="fName_4">gard</div>
<div id="lName_2">sdaf</div><div id="fName_2">radg</div>
</div>
Now I think you all can help me in a better way.
this is a sample example:
html:
<div id="containerDiv">
<div>2</div>
<div>3</div>
<div>1</div>
</div>
js
$(function() {
var container, divs;
divs = $("#containerDiv>div").clone();
container = $("#containerDiv");
divs.sort(function(divX, divY) {
return divX.innerHTML > divY.innerHTML;
});
container.empty();
divs.appendTo(container);
});
you may set your divs.sort function param depend on your goal.
jsFiddle.
and a jQuery Plugin is suitable
I suggest you read the div values so you get an array of objects (persons for example) or just names and perform a sort operation on that. Than...output the result to the initial div (overwriting the default values).
I have built a jQuery sort function in which you can affect the sort field.
(it rebuilds the html by moving the row to another location).
function sortTableJquery()
{
var tbl =$("#tbl tr");
var store = [];
var sortElementIndex = parseFloat($.data(document.body, "sortElement"));
for (var i = 0, len = $(tbl).length; i < len; i++)
{
var rowDom = $(tbl).eq(i);
var rowData = $.trim($("td",$(rowDom)).eq(sortElementIndex).text());
store.push([rowData, rowDom]);
}
store.sort(function (x, y)
{
if (x[0].toLowerCase() == y[0].toLowerCase()) return 0;
if (x[0].toLowerCase() < y[0].toLowerCase()) return -1 * parseFloat($.data(document.body, "sortDir"));
else return 1 * parseFloat($.data(document.body, "sortDir"));
});
for (var i = 0, len = store.length; i < len; i++)
{
$("#tbl").append(store[i][1]);
}
store = null;
}
Every time I need to sort lists I use ListJs.
It's well documented, has good performance even for large lists and it's very lightweight (7KB, despite being library agnostic).

Categories

Resources