The script in this fiddle takes a long text and breaks it up in different divs. It does that by cloning the whole text in each div and incrementing the margin for each page so that only the required text is displayed. Like so:
for (var i = 2; i < page_no + 1; i++) {
$("#stuff").append("<div id='page" + i + "' class='mydiv'></div>");
var copy = $("#page1").clone().attr("id", "onecopy").css({
"margin-top": '-' + (214 * (i - 1)) + 'px',
"height": (214 * 2 * (i - 1)) + 'px'
});
$("#page" + (i)).append(copy);
}
The problem is that the text gets 'clipped' by the overflow/hidden property.
Is there a way so that the first line on a page is 'truncated' if clipped and that the last line is displayed fully if it is clipped?
Any workaround this most annoying of issues would be greatly appreciated.
You can prevent the clipping by adding a line-height style, which is a factor of mydiv's height.
To avoid problems with fractional point sizes, I've changed your code from 214px to 220px, and I set line-height as 22px:
.mydiv {
width: 200px;
height: 220px;
border:solid 1px black;
overflow:hidden;
line-height: 22px;
}
$(function () {
var page_no = Math.ceil($("#fullpage").height() / 220);
for (var i = 2; i < page_no + 1; i++) {
$("#stuff").append("<div id='page" + i + "' class='mydiv'></div>");
var copy = $("#page1").clone().attr("id", "onecopy").css({
"margin-top": '-' + (220 * (i - 1)) + 'px',
"height": (220 * 2 * (i - 1)) + 'px'
});
$("#page" + (i)).append(copy);
}
});
Fiddle
Update
Your method of cloning the text and offsetting it by a top margin is clever, but it can lead to the clipping problems you experienced. An alternative is to add only the text needed to each "page" div.
You can do so by adding the words one at a time until they overflow the div. You can test for the overflow condition by comparing the div's height to its scrollHeight.
The code below accomplishes this:
function newPage() {
pageNo++;
return $('<div id="page'+pageNo+'" class="mydiv">')
.appendTo('#stuff');
};
var words= $('#fullpage').text().split(' '),
pageNo= 0,
page= newPage(),
i,
len;
for(i = 0 ; i < words.length ; i++) {
len= page.text().length;
page.append(words[i]+' ');
if(page[0].scrollHeight > page.height()) {
page.html(page.text().substr(0,len));
i--;
page= newPage();
}
}
Fiddle
Related
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.
I'm trying to make a slide show using multiple background-images and using the background-position property to animate them. Here is the code:
HTML:
<div class="slide_holder" id="slide_holder"></div>
CSS:
.slide_holder {
float: left;
width: 1440px;
height: 720px;
background-image: url("images/gc-h-s-01.jpg"), url("images/gc-h-s-02.jpg"), url("images/gc-h-s-03.jpg");
background-repeat: no-repeat;
background-size: 100%;
background-position: 0px, 1440px, 2880px;
transition: 1s;
}
JS:
var imageIndex = 1;
var x;
var PosValues = ["0px, 1440px, 2880px", "-1440px, 0px, 1440px", "-2880px, -1440px, 0px"]
startSlides();
function startSlides() {
x = setInterval(IncAndWrite, 1000);
}
function IncAndWrite() {
var i;
document.getElementById("slide_holder").style.backgroundPosition = PosValues[imageIndex];
imageIndex++;
if (imageIndex > 2) {imageIndex = 0;}
}
The concept is that the background-position values for each background-image change every 1s keeping only one image in the visible frame.
The above mentioned code works just fine, but I do not want to write individual position values for different screen sizes (as my website is responsive). So I wrote the following code:
JS:
var imageIndex = 1;
var x;
var UnitRes = 1440;
var PosValues = [
UnitRes*0 + "px, " + UnitRes*1 + "px, " + UnitRes*2 + "px;",
UnitRes*(-1) + "px, " + UnitRes*0 + "px, " + UnitRes*1 + "px;",
UnitRes*(-2) + "px, " + UnitRes*(-1) + "px, " + UnitRes*0 + "px;"]
startSlides();
function startSlides() {
x = setInterval(IncAndWrite, 1000);
}
function IncAndWrite() {
var i;
document.getElementById("slide_holder").style.backgroundPosition = PosValues[imageIndex];
imageIndex++;
if (imageIndex > 2) {imageIndex = 0;}
}
The basic concept is that you put the width of the container in UnitRes and then the values get calculated. But this does not seem to work. The background-position values don't change at all.
What I thought was causing the problem:
In the second case of js code I'm putting a variable value inside an array which I thought is not being converted to a string type while inputing it in the CSS syntax.
What I tried doing:
I used typeof but it is showing the type as string
Then I tried using:
document.getElementById("slide_holder").style.backgroundPosition = PosValues[imageIndex].valueOf();
but still it's not working. I also used alert(PosValues[imageIndex]); to check if the values are ok and they are.
Please help me.
The problem was that in first time you have defined parameters without semicolon ; and in second example you have placed it what broke the script.
I have the following code that runs a loop and updates the page as it goes. At the moment the page does not update until the entire loop has run its course.
As you can see, I tried adding a draw function drawValues that is called every 5000 times to draw the current values to the screen. My understanding is that when drawValues is updated, the page should update and then the main loop will resume with its calculations until another 5000 loops.
At the moment the page will not update until the loop runs in its entirety, somehow ignoring every other call to drawValues
Full Snippet:
/*jslint browser: true*/
/*global $, jQuery, alert*/
$(document).ready(function() {
'use strict';
var namesAtStart = ["Sam", "John"],
specialNum = 8,
amountOfNames = namesAtStart.length,
counter = [],
renderCounter = 0,
x,
a,
loopLength,
number,
id,
preId = "content_",
finalId;
for (a = 0; a < amountOfNames; a += 1) {
counter.push(0);
}
for (x = 1; x <= specialNum; x += 1) {
// Start the counter array at zero
for (a = 0; a < amountOfNames; a += 1) {
counter[a] = 0;
}
loopLength = Math.pow(10, x);
finalId = preId + loopLength.toString();
$(".output-small").append('<span id="' + finalId + '"></span>');
for (a = 0; a < loopLength; a += 1) {
number = Math.floor((Math.random() * amountOfNames) + 1);
counter[number - 1] += 1;
renderCounter += 1;
if (renderCounter == 5000) {
drawValues(namesAtStart, counter, finalId, x, a);
}
if (a == loopLength - 1) {
// This is where I am trying to make the code non blocking and async
drawValues(namesAtStart, counter, finalId, x, a);
}
}
}
});
// This is the part that I want to run when called and update page.
function drawValues(names, counter, finalId, id, currentCount) {
'use strict';
var a;
$("#" + finalId).empty();
$("#" + finalId).append("<h3>" + Math.pow(10, id).toLocaleString() + "</h1>");
for (a = 0; a < names.length; a += 1) {
$("#" + finalId).append(
names[a] + ": " + counter[a].toLocaleString() + " (" + (counter[a] / currentCount * 100).toFixed(2) + "%)</br>"
);
}
$("#" + finalId).append("Numerical Difference: " + Math.abs(counter[0] - counter[1]) + "</br>");
$("#" + finalId).append(
"Percentage Difference: " + Math.abs(
(counter[0] / currentCount * 100) - (counter[1] / currentCount * 100)
).toFixed(6) + "%</br>"
);
$("#" + finalId).append("</br>");
}
body {} p,
h3 {
padding: 0px;
margin: 0px;
}
.container {} .output {} .output-small {
margin: 20px;
padding: 5px;
border: 1px solid rgba(0, 0, 0, 1);
width: 300px;
border-radius: 10px;
}
#stats-listing {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<title>Roll The Dice</title>
<body>
<div class="container">
<div class="output" id="stats-listing">
<div class="output-small"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="logic.js"></script>
</body>
</html>
The main UI thread in browsers, which is used to run JavaScript, is single-threaded. So if you have a function that's taking a lot of time, the browser doesn't update the display.
To give the browser a chance to update the display, you need to yield back to it by letting your current function end and scheduling a timed callback to another run of it for the next block of updates, via setTimeout. You'll have to experiment with the browsers you want to support to determine the delay in the timed callback; some browsers are happy with 0 (call back as soon as possible), others want longer (50 — 50 milliseconds — is plenty for every browser I know).
Here's a simple example that adds 10 boxes to the page, yields, then adds another 10, yields, etc. until it's done 1,000 boxes:
(function() {
var total = 0;
addBoxes();
function addBoxes() {
var n;
for (n = 0; n < 10 && total < 1000; ++n, ++total) {
box = document.createElement('div');
box.className = "box";
document.body.appendChild(box);
}
if (total < 1000) {
setTimeout(addBoxes, 10); // 10ms
}
}
})();
.box {
display: inline-block;
border: 1px solid green;
margin: 2px;
width: 20px;
height: 20px;
}
origin
result
I want to split a string into character, and make each of the character fit the container equally, this is my work for the time being: http://jsfiddle.net/d5fu9/
The first item must attached to the left, and the last item must attached to the right.
$.fn.textjustify = function() {
return this.each(function() {
var text = $(this).text(),
containerWidth = $(this).width(),
character = '',
string = '',
singleWidth = 0,
firstItemWidth = 0,
lastItemWidth = 0,
alignWidth = 0;
if ('' !== text) {
$(this).css('position', 'relative');
textArray = text.split('');
singleWidth = Math.floor(containerWidth / textArray.length);
for (i in textArray) {
// Wrapp with div to get character width
character = ('' === $.trim(textArray[i])) ? ' ' : textArray[i];
string += '<span>' + character + '</span>';
}
$(this).html(string);
firstItemWidth = $(this).find('span:first').width();
lastItemWidth = $(this).find('span:last').width();
alignWidth = containerWidth - (firstItemWidth + lastItemWidth);
$(this).find('span').each(function(i) {
if (0 === parseInt(i)) {
// The first item
$(this).css({position: 'absolute', left: 0, top: 0});
} else if ((parseInt(textArray.length) - 1) === parseInt(i)) {
// The last item
$(this).css({position: 'absolute', right: 0, top: 0});
} else {
// Other items
// stuck in here......
var left = (i * singleWidth) - $(this).width() + firstItemWidth;
$(this).css({position: 'absolute', left: left, top: 0});
}
});
}
});
}
stuck in the algorithm of middle items's position.
I think this is the simplest solution.
Works great with All browsers (IE included)
without complex (and unreliable) width detection and calculation.
without specifying the words width/height
without relative/absolute positioning
using pure HTML/CSS/JS/JQ tricks.
Working Fiddle
HTML:(very simple)
<div class="Box">
<div class="Centered">
<div class="Spread">Lighting</div>
<div class="Spread">我是中文</div>
</div>
</div>
CSS:(neat and tricky)
*
{
margin: 0;
padding: 0;
}
.Box
{
width: 150px;
height: 150px;
border: 1px solid red;
margin: 6px;
}
.Box:before
{
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-left: -5px;
}
.Centered
{
display: inline-block;
vertical-align: middle;
width: 100%;
}
.Spread
{
width: 100%;
text-align: justify;
font-size: 0;
}
.Spread span
{
font-size: medium;
}
.Spread:after
{
content: '';
display: inline-block;
height: 0px;
width: 100%;
}
JS/JQ:
$.fn.SplitText = function () {
return this.each(function () {
return $(this).html('<span>' + $(this).text().split('').join(' ') + '</span>');
});
}
$(function () {
$('.Spread').SplitText();
})
Explanations:
as mentioned by wared in the comments, IE7 doesn't support the use of pseudo classes.
but they are not necessary for the solution. Here's a Fiddle for IE7 (and all other browsers of course).
how the vertical aligning works?
when vertical-align:middle; is used on an inline element, it will align the middle of this element with the other inline elements in the same line.
that's why I'm creating an inline element with height:100%;, so when we align our inline element to his middle, it will actually be the middle of the container.
how the horizontal distribution works?
taking advantage of the text-align:justify;,
we create an empty inline element (height:0;) with width:100%;, we can imagine that it takes a full line, and the rest of the text takes the second line.
using justify makes the second line spread evenly to take the exact space as the first.
let me know if you need more explanation.
I added a fixed with for spanelements for the widest char which was W in your fiddle with 15px.
span {
width: 15px;
}
Then substracted 20px from container width which will be the free space on the sides later.
singleWidth = Math.floor((containerWidth-20) / textArray.length);
Added this extra Space to the firstitemWidth so that the other chars align correctly:
firstItemWidth = $(this).find('span:first').width() + 10;
And set the position of first and last to 10 from left and right here:
if (0 === parseInt(i)) {
// The first item
$(this).css({position: 'absolute', left: 10, top: 0});
} else if ((parseInt(textArray.length) - 1) === parseInt(i)) {
// The last item
$(this).css({position: 'absolute', right: 10, top: 0});
Here is the updated Fiddle
I hope this will work out for you ;)
I have made a script for you if you do not mind left and right spaces. You can set the right and left margins making some little modifications.
$(document).ready(function(){
var txt = $(".container").text(); //get the text
var txt2 = "";
var len = txt.length;
$(".container").empty(); //clear the content
for(i=0; i<len; i++) //surround all characters with span
{
txt2 += "<span>" + txt.substr(i,1) + "</span>";
}
$(".container").html(txt2);
$("span").css({"width": Math.round($(".container").width())/len + "px", "display":"inline-block", "text-align":"center"});
});
Fiddle is here
Try this:
DEMO: http://jsfiddle.net/jc2mm/4/
JS:
$(".spread").each(function(idx, elem) {
var titleElem = $(this),
titleStr = titleElem.html(),
charWidth = Math.floor(($(".box").width() / titleStr.length) * 100) / 100;
titleElem.html("");
for(var i = 0; i < titleStr.length; i++) {
titleElem.append($("<span>", {"class" : "singleChar"}).css("width", charWidth).html(titleStr[i]));
}
});
CSS:
.box {
width: 150px;
height: 150px;
border: 1px solid red;
margin: 6px;
}
.title {
margin-top: 40px;
height: 16px;
}
.singleChar {
float: left;
text-align: center;
display: block;
min-height: 1px;
}
Try this: http://jsfiddle.net/d5fu9/5/
Each character is contained in a box of width singleWidth, left is computed counting the preceding character boxes, characters are centered.
Changes:
$(this).css({width: singleWidth,position: 'absolute', left: 0, top: 0});
and
var left = i* singleWidth + (i-1)*(textArray.length-2)/(textArray.length+1);
and in CSS:
.spread {
text-align: center;
}
Here is another version http://jsfiddle.net/d5fu9/6/ where leftmost and rightmost characters are attached to the border.
Modified width of a single character container:
singleWidth = Math.floor((containerWidth -firstItemWidth - lastItemWidth)/ (textArray.length-2));
and how much each inner character moves from the left:
var left = firstItemWidth+(i-1)* singleWidth ;
I've made this stuff : http://jsfiddle.net/wared/HDbA5/.
The idea is to use paddings to create space between chars. Tested with Chrome only. It seems to fail when the DIV has no explicit fixed width, and sometimes there is one pixel remaining, I haven't investigated. Lastly, this script does not support single characters. If you're interested in this answer, this job is for you :)
I must show some code to be able to post this answer, so, here it is :
<div><span>hello</span></div>
jQuery.fn.justify = function () {
return this.each(function () {
var el = $(this),
ct = el.parent(),
chars = el.text().split(''),
bits = (chars.length - 1) * 2,
freeSpace = ct.width() - el.width(),
bitWidth = Math.floor(freeSpace / bits),
gap = freeSpace % bits;
el.html(jQuery.map(chars, function (char, i) {
var paddings = ['0', null, '0', null];
if (!i) {
paddings[1] = (bitWidth + (gap && (--gap, 1))) + 'px';
paddings[3] = '0';
} else if (i + 1 === chars.length) {
paddings[1] = '0';
paddings[3] = (bitWidth + (gap && (--gap, 1))) + 'px';
} else {
paddings[1] = (bitWidth + (gap && (--gap, 1))) + 'px';
paddings[3] = (bitWidth + (gap && (--gap, 1))) + 'px';
}
return '<span style="padding:' + paddings.join(' ') + '">' + char + '</span>';
}).join(''));
});
};
A "bit" is a portion of the free space. It's half the space between two characters :
"abc" : 4 bits ("a..b..c").
"ab cd" : 8 bits ("a..b.. ..c..d").
The "gap" is the number of pixels remaining after splitting the free space into bits. Those pixels are assigned to each "bit" until no pixels remain. Let's say gap = 1 :
bitWidth + (gap && (--gap, 1)) // gap = gap - 1 THEN bitWidth + 1
// next bit
bitWidth + (gap && (--gap, 1)) // bitWidth + 0
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