javascript algorithm to auto fit multiple images - javascript

I was looking for a function which would take the overall width, max height, min height parameters as the input and fit multiple images in the given overall width adjusting their width.
So for an example in this page , all the images (in same row) should get auto adjusted to the same height keeping their original aspect ratio with javascript changing their widths.
Edit: I have Answered

You need only to change the height of the picture. The aspect ratio remains.
function height100() {
var imgages = document.getElementsByTagName('img');
Array.prototype.forEach.call(imgages, function (a) {
a.style.height = '100px';
});
}
<button onclick="height100();">100px height</button><br>
<img src="http://lorempixel.com/400/200/">
<img src="http://lorempixel.com/100/200/">
<img src="http://lorempixel.com/300/200/">
<img src="http://lorempixel.com/400/300/">
<img src="http://lorempixel.com/400/150/">
<img src="http://lorempixel.com/800/200/">
<img src="http://lorempixel.com/450/200/">
<img src="http://lorempixel.com/400/250/">

You dont necessarily need JS to accomplish this, unless your height is dynamic.
Flexbox should be able to take care of it for you.
Here is what you could do.
div {
border: 1px solid black;
display: flex;
flex-flow: row wrap;
}
img {
border: 1px solid red;
max-width: 100%;
height: 100px;
}
<div>
<img src="http://lorempixel.com/400/200/">
<img src="http://lorempixel.com/100/200/">
<img src="http://lorempixel.com/300/200/">
<img src="http://lorempixel.com/400/300/">
<img src="http://lorempixel.com/400/150/">
<img src="http://lorempixel.com/800/200/">
<img src="http://lorempixel.com/450/200/">
<img src="http://lorempixel.com/400/250/">
</div>
If you are looking for a dynamic height, just set the height at run time and could do something like this.
var imgs = document.querySelectorAll('img');
[].forEach.call(imgs, function(img) {
img.style.height = "100px";
});
div {
border: 1px solid black;
display: flex;
flex-flow: row wrap;
}
img {
border: 1px solid red;
max-width: 100%;
}
<div>
<img src="http://lorempixel.com/400/200/">
<img src="http://lorempixel.com/100/200/">
<img src="http://lorempixel.com/300/200/">
<img src="http://lorempixel.com/400/300/">
<img src="http://lorempixel.com/400/150/">
<img src="http://lorempixel.com/800/200/">
<img src="http://lorempixel.com/450/200/">
<img src="http://lorempixel.com/400/250/">
</div>

As stated in the other answers, it's a trivial job to adjust images to have the same height. Once you have scaled the images to have same height, according to their individual aspect ratio they will have different widths. Assuming that you have a certain width per row of images you might do as follows to distribute the images to the rows such that rows evenly get populated with the maximum amount of image and minimum white space.
function lineUpImages(imageWidths,totalWidth){
var sum = imageWidths.reduce((p,c) => p+c),
avg = sum/imageWidths.length;
initial = [...Array(Math.ceil(avg))].map(sa => (sa = [], sa.sum = 0, sa)); // initial rows array
return imageWidths.sort((a,b) => b-a)
.reduce((lines,image) => { var line = lines.reduce((p,c) => p.sum < c.sum ? p : c);
line.push(image);
line.sum += image;
return lines;
},initial);
}
var imageWidths = [...Array(20)].map(_ => ~~(Math.random()*4)+2), // generate a random array of image width values
result = lineUpImages(imageWidths,20); // maximum row width allowed is 20
console.log("Image Widths: :", JSON.stringify(imageWidths));
console.log("Rows:", JSON.stringify(result));
You might also chain up a map instruction to the very end and shuffle the images in each row (shuffling the sub arrays).

The answer so that images are of constant height and fills the outer div.
The example here
The javscript here -
$(function(){
//var pics;
var pic1 = {height:"10", width:"20", ap:1.374, rh:0};
var pics = [pic1];
//pics.push(pic3);
//$('#test').html(pics[2].height);
$('#some').imagesLoaded(function() {
$('#test').html('test ');
$('#some img').each(function(index) {
//setting const height
$(this).height(150);
var apic = {height:$(this).height() , width: $(this).width() ,ap: $(this).width() / $(this).height() , rh:0};
pics.push(apic);
});
$('#test').append(pics.length+ '<br />');
for (var j=1; j <pics.length;j++) {
$('#test').append(pics[j].width + ' ' + pics[j].ap + '<br />');
}
$('#test').append('Calculating width ' + '<br />');
var set = [0];
for (var j=1; j <pics.length;j++) {
var t = 0;
var c = j
do {
t = t+ pics[c].width;
$('#test').append(c + ' ' + t+ '<br />');
c=c+1;
}while (t < 645 && c<pics.length);
c=c-1;
if(t>645) {
c = c -1;
}
set.push(c);
j = c;
}
$('#test').append('Sets are: <br />');
var v = 1;
var st = 0;
for (p = 1; p<set.length; p++) {
$('#test').append(set[p] + ' ');
st = v;
v = set[p];
$('#test').append(p + ': ');
var tot = 0;
var inc = 0;
while(tot < 645 ) {
var tot1=0;
for(var g = st; g<v+1; g ++) {
tot1 =tot1+ (pics[g].ap * (pics[g].height+inc));
}
tot=tot1;
inc = inc+1;
}
for(var g = st; g<v+1; g ++) {
$('#some img').eq(g-1).height ( 150 + inc);
}
$('#test').append( '<br / >');
v = v+1;
}
$('#test').append('<br />');
/*
var tot = 0
var wid;
var wid1;
var inc=0;
var r = 1;
for (r =1; r<pics.length-1; r++) {
inc = 0;
tot = 0;
while ( tot < 645) {
wid = pics[r].ap * (pics[r].height+inc);
wid1 = pics[r+1].ap * (pics[r+1].height+inc);
tot = wid + wid1;
inc = inc+ 1;
}
$('#test').append('Total ' + inc +' '+ wid + ' ' + wid1 + '<br />');
$('#some img').eq(r-1).height ( 150 + inc);
$('#some img').eq(r).height ( 150 + inc);
r=r+1;
*/
}
);
});

Related

how to adjust text height to div using javaScript

I have some articles on the block. Some of them cut in the middle of their hight like on the picture:
I tried to fix this problem by using the function below, but it still doesn't work.
const setSameHeightToAll = function() {
const all = document.querySelectorAll('.text_blog')
let maxHeight = 0
var length = all.length
for (var i = 0; i < length; i++) {
if (all[i].getBoundingClientRect().height > maxHeight) {
maxHeight = all[i].getBoundingClientRect().height
}
}
for (var j = 0; j < length; j++) {
all[j].setAttribute('style', 'height:' + maxHeight + 'px')
}
}
in html:(this is pug.js)
.text_blog
!= post.content.full
p.read_more
a(href='/blog/'+post.key) leia mais >>
this is css:
.text_blog {
overflow: hidden;
height: 112px;
}
How can I change my function to work correctly.
You're setting the max-height to 0 in your javascript code.
Not knowing the full context of your code, because you only posted the javascript part, You may either have a constant height for all '.text_blog' elements or use
CSS
.text_blog{
height: auto;
overflow: scroll;
}
OR
JAVASCRIPT
const setSameHeightToAll = function() {
const all = document.querySelectorAll('.text_blog')
//GET HEIGHT OF FIRST ELEMENT AND MAKE IT UNIFORM
let maxHeight = all.firstElementChild.offsetHeight;
//SET CONSTANT HEIGHT
let maxHeight = '500px';
var length = all.length;
for (var i = 0; i < length; i++) {
all[i].setAttribute('style', 'height:' + maxHeight + 'px')
}
}
You are also forgetting to include the closing ';' at the end of some lines.

Is there a way to combine multiple divs into one

I have a dynamic group of n by m divs to form a grid. The items in this grid can be selected. The end result which I am hoping to achieve is to be able to combine and split the selected divs.
I have managed to get the divs to show correctly and select them, storing their id's in a list. Is there a way I could combine the selected divs, keeping the ones around it in their place?
#(Html.Kendo().Window()
.Name("window") //The name of the window is mandatory. It specifies the "id" attribute of the widget.
.Title("Dashboard Setup") //set the title of the window
.Content(#<text>
<div id="divSetup">
<div class="dvheader">
<b>Dashboard Setup</b>
</div>
<div>
<p>Enter the number of columns and rows of dashboard elements. This will create an empty dashboard with a set number of items which can be filled with KPI charts.</p>
<br />
<div class="dvform">
<table>
<tr style="margin-bottom: 15px;">
<td>
#Html.Label("Number of Columns: ")
</td>
<td>
<input type="number" name="NumColumns" id="NoColumns" min="1" max="20" />
</td>
</tr>
<tr style="margin-bottom: 15px;">
<td>
#Html.Label("Number of Rows: ")
</td>
<td>
<input type="number" name="NumRows" id="NoRows" min="1" max="20" />
</td>
</tr>
</table>
</div>
</div>
<div style="float: right">
<button id="btnSave" class="k-primary">Save</button>
<button id="btnClose">Close</button>
</div>
</div>
</text>)
.Draggable() //Enable dragging of the window
.Resizable() //Enable resizing of the window
.Width(600) //Set width of the window
.Modal(true)
.Visible(false)
)
<div id="dashboard">
</div>
<button id="combine" title="Combine">Combine</button>
<script>
$(document).ready(function () {
debugger;
$("#window").data("kendoWindow").open();
$("#btnClose").kendoButton({
click: close
});
$("#btnSave").kendoButton({
click: Save
});
$("#combine").kendoButton();
});
var array = [];
function clicked(e)
{
debugger;
var selectedDiv = "";
var x = document.getElementsByClassName('column')
for (var i = 0; i < x.length; i++)
{
if (x[i].id == e.id)
{
x[i].classList.add("selected");
array.push(x[i]);
}
}
for (var x = 0; x < array.length - 1; x++) {
array[x].classList.add("selected");
}
}
function close() {
$("#window").hide();
}
function Save()
{
debugger;
var col = document.getElementById("NoColumns").value;
var row = document.getElementById("NoRows").value;
for (var x = 1; x <= row; x++)
{
debugger;
document.getElementById("dashboard").innerHTML += '<div class="row">';
debugger;
for (var i = 1; i <= col; i++)
{
document.getElementById("dashboard").innerHTML += '<div onclick="clicked(this)" id="Row ' + x + ' Col ' + i + '" class="column">' + i + '</div>';
}
document.getElementById("dashboard").innerHTML += '</div>';
}
}
<style>
.selected {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
#dashboard {
width: 80%;
margin: auto;
background-color: grey;
padding: 20px;
}
* {
box-sizing: border-box;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
padding: 20px;
border: 1px black solid;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
Below is an image of the selected blocks I would like to combine into one, while keeping it's place
If you were using a table it would be much easier, for div's, I can think of a solution if the style position is absolute, maybe it would help you start at least.
<div id="container"></div>
<button id="combine" title="Combine" disabled="disabled">Combine</button>
<div id="output"></div>
the script:
<script>
var cc;
function group() {
var xx = $(".selected").map(function () { return $(this).attr("data-x"); }).get();
var yy = $(".selected").map(function () { return $(this).attr("data-y"); }).get();
this.minX = Math.min.apply(Math, xx);
this.minY = Math.min.apply(Math, yy);
this.maxX = Math.max.apply(Math, xx);
this.maxY = Math.max.apply(Math, yy);
this.selectedCount = $(".selected").length;
this.CorrectGroup = function () {
var s = this.selectedCount;
return s == this.cellsCount() && s > 1;
}
this.width = function () {
return this.maxX - this.minX + 1;
}
this.height = function () {
return this.maxY - this.minY + 1;
}
this.cellsCount = function () {
return this.width() * this.height();
}
}
function cell(x, y, g) {
this.x = x;
this.y = y;
this.g = g;
this.spanX = 1;
this.spanY = 1;
this.visible = true;
var cellWidth = 80;
var cellHeight = 50;
this.div = function () {
var output = jQuery('<div/>');
output.attr('id', 'y' + y + 'x' + x);
output.attr('data-x', x);
output.attr('data-y', y);
output.attr('style', this.left() + this.top() + this.width() + this.height());
output.addClass('clickable');
output.html('(y=' + y + ' x=' + x + ')')
return output;
}
this.left = function () {
return 'left:' + (x * cellWidth) + 'px;';
}
this.top = function () {
return 'top:' + (100 + y * cellHeight) + 'px;';
}
this.width = function () {
return 'width:' + (this.spanX * cellWidth) + 'px;';
}
this.height = function () {
return 'height:' + (this.spanY * cellHeight) + 'px;';
}
}
function cells(xx, yy) {
this.CellWidth = xx;
this.CellHeight = yy;
this.CellList = [];
for (var y = 0; y < yy; y++)
for (var x = 0; x < xx; x++) {
this.CellList.push(new cell(x, y, 1));
}
this.findCell = function (xx, yy) {
return this.CellList.find(function (element) {
return (element.x == xx && element.y == yy);
});
}
this.displayCells = function (container) {
container.html('');
for (var y = 0; y < yy; y++)
for (var x = 0; x < xx; x++) {
var cell = this.findCell(x, y);
if (cell.visible)
cell.div().appendTo(container);
}
}
}
$(document).ready(function () {
$('#combine').click(function () {
$(".selected").each(function () {
var x = $(this).data('x');
var y = $(this).data('y');
var cell = cc.findCell(x, y);
cell.visible = false;
cell.g = 'y';
});
var first = $(".selected").first();
var xx = $(first).data('x');
var yy = $(first).data('y');
var cell = cc.findCell(xx, yy);
var g = new group();
cell.visible = true;
cell.g = xx + '_' + yy;
cell.spanX = g.width();
cell.spanY = g.height();
cc.displayCells($('#container'));
});
//make divs clickable
$('#container').on('click', 'div', function () {
$(this).toggleClass('selected');
if (CheckIfSelectedAreGroupable())
$('#combine').removeAttr("disabled");
else
$('#combine').attr("disabled", "disabled");
});
cc = new cells(12, 10);
cc.displayCells($('#container'));
});
function CheckIfSelectedAreGroupable() {
var g = new group();
return g.CorrectGroup();
}
</script>
Style:
<style>
.selected {
background-color: #226fa3 !important;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
.clickable {
border: 1px solid lightgray;
margin: 0px;
padding: 0px;
background-color: lightyellow;
position: absolute;
}
</style>
Im starting the divs by the following line, you can hock your form to trigger something similar.
cc = new cells(12, 10);
the combine button will not activate if you dont select a correct group, a rectangle shape selection.
the split will not be hard too but I did not have time to put it together, if this solution help, I can update it for the split.
Note: I wrote this quickly so its not optimized.
to try the solution use :
jsfiddle

Creating gallery in html DOM with javascript

I want create in html tags which will create gallery,I have 7 images and I want this images will display one time.this means this code must output 3 rows 7 images.
var img=["sea.jpg","monkey.jpg","birtday.jpg","picture.jpg","nintendo.png","square.png","chrome.png"];
function gallery(galleryWidth,columnCount,gutter,divCount){
var n=0;
document.write('<div class="gallery"style="width:'+galleryWidth+'px">');
while(n<img.length%columnCount){
document.write('<div class="row">');
for(i=0;i<img.length;i++){
document.write('<div class="galItem"style="width:'+(galleryWidth/columnCount-2*gutter)+'px;margin:'+gutter+'px"> <img src="img/'+img[i]+'"/></div>');
img.shift();
}
document.write('</div>');
document.write('<div class="clear"></div>');
n++;
}
document.write("</div>");
}
gallery(240,3,5,7);
your code seem like this.
var img = ["sea.jpg", "monkey.jpg", "birtday.jpg", "picture.jpg", "nintendo.png", "square.png", "chrome.png"];
function gallery(galleryWidth, columnCount, gutter) {
document.write('<div class="gallery" style="width:' + galleryWidth + 'px">');
for (var j = 0; j < img.length; j++) {
var startNewLine = j && !(j % columnCount);
if (startNewLine) {
document.write('<div class="row">');
}
document.write('<div class="galItem" style="width:' + (galleryWidth / columnCount - 2 * gutter) + 'px;margin:' + gutter + 'px"> <img alt="' + img[j] + '"/></div>');
if (startNewLine) {
document.write('</div>');
document.write('<div class="clear"></div>');
}
}
document.write("</div>");
}
gallery(240, 3, 5, 7);
.row {
display: block;
clear: both;
}
.clear {
height: 0;
}
img {
width: 100%;
height: 100%;
min-height:30px;
}
.galItem {
float: left;
}
First thing, avoid document.write. There are far more reliable ways of doing this. Second, do/while and your for loop seem to be getting tangled. This may be what you're trying to do.
var img = ["sea.jpg",
"monkey.jpg",
"birtday.jpg",
"picture.jpg",
"nintendo.png",
"square.png",
"chrome.png"
];
function gallery(galleryWidth, columnCount, gutter, divCount) {
this.width = galleryWidth;
this.cols = columnCount;
this.gutter = gutter;
this.divs = divCount;
var myRow, myDiv, myImg, myClearDiv;
var n = 0;
var myGallery = document.createElement('div');
myGallery.classList.add('gallery');
myGallery.style.width = this.width + "px";
myRow = document.createElement('div');
myRow.classList.add('row');
for (i = 0; i < img.length; i++) {
if (n >= this.cols) {
myGallery.appendChild(myRow);
myClearDiv = document.createElement("div");
myClearDiv.classList.add("clear");
myGallery.appendChild(myClearDiv);
myRow = document.createElement('div');
myRow.classList.add('row');
n = 0;
}
myDiv = document.createElement('div');
myDiv.classList.add('galItem');
myDiv.style.width = this.width / this.cols - 2 * this.gutter + 'px';
myDiv.style.margin = this.gutter + 'px';
// Create the image element, and append it...
myImg = document.createElement('img');
myImg.src = '"img/' + img[i] + '"';
myDiv.appendChild(myImg);
// then, append the div to the row.
myRow.appendChild(myDiv);
n++;
}
myGallery.appendChild(myRow);
myClearDiv = document.createElement("div");
myClearDiv.classList.add("clear");
myGallery.appendChild(myClearDiv);
myRow = document.createElement('div');
myRow.classList.add('row');
var container = document.getElementById("container");
container.appendChild(myGallery);
}
gallery(600, 3, 5, 4);
.galItem {
width: 50px;
height: 50px;
display: inline;
border: 1px dotted blue;
}
<div id="container">
</div>

only first element in jquery each loop getting updated

Hi I am just trying to do an each loop on elements containing the class front but only first element is getting updated for some reason please help. May be it is a silly mistake but i am unable to find it.
jsfiddle:
http://jsfiddle.net/sVTCK/7/
HTML:
<div class="wrapper">
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
<div class="front"></div>
</div>
jquery:
function setSlide(rows, dimension) {
var topPos = 0;
var leftPos = 0;
$(".front").each(function(i, e) {
topPos++;
if (i % rows === 0) {
topPos = 0;
leftPos++;
}
var position = topPos * dimension + " " + (leftPos - 1) * dimension;
e.style.backgroundPosition = position;
e.innerHTML = e.style.backgroundPosition;
});
}
setSlide(3,200);
css:
.front{
width:200px;
height:200px;
background:url(some image);
border:1px solid black;
float:left
}
.wrapper{
overflow:hidden;
width:610px;
}
function setSlide(rows, dimension) {
var topPos = 0;
var leftPos = 0;
$(".front").each(function(i, e) {
topPos++;
if (i % rows === 0) {
topPos = 0;
leftPos++;
}
var position = topPos * dimension + 'px ' + (leftPos - 1) * dimension +'px';
e.style.backgroundPosition = position;
e.innerHTML = e.style.backgroundPosition;
});
}
setSlide(3,200);
THE WORKING DEMO.
ok I've refractored the javascript stlightly into jquery since your using it and moved from the vanilla javascript:
function setSlide(rows, dimension) {
var topPos = 0;
var leftPos = 0;
var front = $('.front');
$.each(front, function(index, val) {
topPos++;
if (index % rows === 0) {
topPos = 0;
leftPos++;
}
var position = topPos * dimension + "px, " + (leftPos - 1) * dimension + 'px';
$(this).css('backgroundPosition', position);
$(this).append(position);
});
}
setSlide(3,200);
http://jsfiddle.net/sVTCK/18/
If you can tell us what your trying to do with the if statement it would help to add the background-position...
You should be reallying on jQuery if you have it in page since it'll be quicker and you should also be caching your variables

Populating page with images using Javascript loop [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm currently writing a website with a friend and I need to create a javascript loop for pulling images out of a database and populating them in xy positions on a grid.
The database we're using is built in python and django but for now I'm trying to get it working with one loop and a test image.
This is the loop in question:
function createImages(){
var picture = document.createElement('img');{
for (var pic=0; pic < 100; pic++) {
pic.pk = 1;
pic.model = 'image';
pic.fields.title = 'Image Test';
pic.fields.timestamp = '2013-01-01T00:00:00.000Z';
pic.fields.image = 'http://i240.photobucket.com/albums/ff301/quyenhiepkhach/CAT.jpg';
pic.fields.height = 30 + 'px';
pic.fields.width = 30 + 'px';
pic.fields.link = '#ImageLink';
pic.fields.board = 1;
pic.fields.posx = 100 + 'px';
pic.fields.posy = 50 + 'px';
pic.fields.owner = 1;
pic.fields.region = 1;
picture.className = 'image-tooltip';
picture.src = pic.fields.image;
picture.style.marginTop = pic.fields.posy;
picture.style.marginLeft = pic.fields.posx;
picture.style.height = pic.fields.height;
picture.style.width = pic.fields.width;
document.body.appendChild(picture);
}
}
};
createimages();
What I have working so far:
Grid that is drawn onto my index page with two sections (prime and
standard).
Mouseover script that displays the xy coords and standard or prime
gridspace. (not working in jsfiddle)
What I have broken so far:
Javascript loop for pulling images out of database and writing them to body of page
Mouseover script to display some of the image data
I've included everything below to make the webpage and also a jsFiddle
HTML HEAD:
<!-- Le random script for mouseover -->
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<!--MOUSEOVER SCRIPT FOR GRID COORDINATES-->
<script>
$(window).load(function(){
var tooltip = $( '<div id="tooltip">' ).appendTo( 'body' )[0];
$( '.coords' ).
each(function () {
var pos = $( this ).offset(),
top = pos.top,
left = pos.left,
width = $( this ).width(),
height = $( this ).height();
$( this ).
mousemove(function ( e ) {
var x = ( (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) - left ) .toFixed( 0 ),
y = ( ( (e.clientY + document.body.scrollTop + document.documentElement.scrollTop) - top ) ) .toFixed( 0 );
if ( x > 20 && x < 481 && y > 20 && y < 321) {
$( tooltip ).text( 'prime | ' + x + ', ' + y ).css({
left: e.clientX + 20,
top: e.clientY + 10
}).show();
}
else {
$( tooltip ).text( 'standard | ' + x + ', ' + y ).css({
left: e.clientX + 20,
top: e.clientY + 10
}).show();
}
}).
mouseleave(function () {
$( tooltip ).hide();
});
});
});
</script>
<!--MOUSEOVER SCRIPT FOR IMAGES-->
<script>
$(window).load(function(){
var imagetooltip = $( '<div id="imagetooltip">' ).appendTo( 'body' )[0];
$( '.image-tooltip' ).
each(function () {
$( imagetooltip ).text( pic.fields.title + ' , ' + pic.fields.link ).css({
left: e.clientX + 20,
top: e.clientY + 10
}).show();
mouseleave(function () {
$( tooltip ).hide();
});
});
});
</script>
CSS:
/* Style for standard section on grid */
.grid {
margin: 0px auto auto;
border: 1px solid #000;
border-width: 0 1px 1px 0;
background-color: #28ACF9;
}
/* Style for grid div */
.grid div {
border: 1px solid #000;
border-width: 1px 0 0 1px;
float: left;
}
/* Style for prime section on grid */
.gridprime {
margin-top: 50px ;
margin-left: 50px;
border: 1px solid #000;
background-color: #FFFF33;
float: left;
}
/* Style for grid coords tooltip */
#tooltip {
text-align:center;
background:black;
color:white;
padding:3px 0;
width:150px;
position:fixed;
display:none;
white-space:nowrap;
z-index:3;
}
/* Style for image tooltip */
#imagetooltip {
text-align:left;
background:#CCC;
color:white;
padding:3px 0;
width:200px;
position:fixed;
display:none;
white-space:nowrap;
z-index:4;
}
HTML BODY:
<!--SCRIPT TO CREATE THE GRID (WORKING)-->
<script type="text/javascript">
function creategrid(size){
var primeW = Math.floor((460) / size),
primeH = Math.floor((300) / size),
standardW = Math.floor((500) / size),
standardH = Math.floor((500) / size);
var standard = document.createElement('div');
standard.className = 'grid coords';
standard.style.width = (standardW * size) + 'px';
standard.style.height = (standardH * size) + 'px';
standard.board = '1';
var prime = document.createElement('div');
prime.className = 'gridprime';
prime.style.width = (primeW * size) + 'px';
prime.style.height = (primeH * size)+ 'px';
prime.style.position = 'absolute'
prime.style.zIndex= '1';
standard.appendChild(prime);
for (var i = 0; i < standardH; i++) {
for (var p = 0; p < standardW; p++) {
var cell = document.createElement('div');
cell.style.height = (size - 1) + 'px';
cell.style.width = (size - 1) + 'px';
cell.style.position = 'relative'
cell.style.zIndex= '2';
standard.appendChild(cell);
}
}
document.body.appendChild(standard);
}
creategrid(10);
</script>
<!--SCRIPT TO LOOP IMAGES OUT OF DATABASE (USING 1 TO TEST FOR NOW)-->
<script type="text/javascript">
function createImages(){
var picture = document.createElement('img');{
for (var pic=0; pic < 100; pic++) {
pic.pk = 1;
pic.model = 'image';
pic.fields.title = 'Image Test';
pic.fields.timestamp = '2013-01-01T00:00:00.000Z';
pic.fields.image = 'http://i240.photobucket.com/albums/ff301/quyenhiepkhach/CAT.jpg';
pic.fields.height = 30 + 'px';
pic.fields.width = 30 + 'px';
pic.fields.link = '#ImageLink';
pic.fields.board = 1;
pic.fields.posx = 100 + 'px';
pic.fields.posy = 50 + 'px';
pic.fields.owner = 1;
pic.fields.region = 1;
picture.className = 'image-tooltip';
picture.src = pic.fields.image;
picture.style.marginTop = pic.fields.posy;
picture.style.marginLeft = pic.fields.posx;
picture.style.height = pic.fields.height;
picture.style.width = pic.fields.width;
if (pic.fields.board = document.body.id);{
document.body.appendChild(picture);
}
}
}
};
createimages();
</script>
Your code is riddled with syntax errors and logic issues. STart by using a browser console to look at errors and fix accordingly.
Also note javascript is case sensitive so if you create a function createImages() you need to use same case to call function. You are calling createimages() which doesn't exist
You can't use pic as variable to create an object in a for loop where pic is the counter.
ALso need to create the new image within the loop, not outside it.
Working code:
//SCRIPT TO LOOP IMAGES OUT OF DATABASE (USING 1 TO TEST FOR NOW)//
function createImages() {
for (var pic = 0; pic < 100; pic++) {
/* new image for each pass of loop*/
var picture = document.createElement('img');
var data = {
pk: 1,
model: 'image',
fields: {
title: 'Image Test',
timestamp: '2013-01-01T00:00:00.000Z',
image: 'http://i240.photobucket.com/albums/ff301/quyenhiepkhach/CAT.jpg',
height: 30 + 'px',
width: 30 + 'px',
link: '#ImageLink',
board: 1,
posx: 100 + 'px',
posy: 50 + 'px',
owner: 1,
region: 1
}
};
picture.className = 'image-tooltip';
picture.src = data.fields.image;
picture.style.marginTop = data.fields.posy;
picture.style.marginLeft = data.fields.posx;
picture.style.height = data.fields.height;
picture.style.width = data.fields.width;
/* comment out "if" since isn't true*/
// if (data.fields.board ==document.body.id) {
document.body.appendChild(picture);
// }
}
}
createImages();
DEMO: http://jsfiddle.net/8eYhK/9/
There are various errors in your code
Here pic is a number, but you seem to be setting properties on it as it was an object literal
for (var pic=0; pic < 100; pic++) {
pic.pk = 1;
This line will also fail as you need to first create the pic.fields object
pic.fields = {}; // <-- add this line
pic.fields.title = 'Image Test';
Your function is called createImages but you're trying to call createimages (case-sensitivity)
I suggest you look at your browser console (usually F12) to check for errors

Categories

Resources