Thanks to a really helpful user on this website (whose name I do not know, but I wish to thank and credit him!), I got the following tip on how to store area elements in an array so that when I mouse over a coordinate, I could display all of the overlay id's of the area elements that existed at that coordinate (even if the area elements were not at the same z-level):
I'm just stuck on one thing- once I have gathered all the elements that exist at the coordinate in the hoveredElements array, how do I show their overlay ids?
EDIT:
Here is an example of the full code (the overlay still does not display when I mouse over)
The file test.txt contains:
cscCSL1A15 700 359 905 318
cscCSL1A14 794 400 905 318
I use the maphilight plugin available online, and blanketaphi.png is the plot I use as a background.
<!DOCTYPE html>
<html>
<head>
<title>Detector Elements</title>
<script type="text/javascript"
src="Demo_imagemap_highlight_files/jquery-1.js"></script>
<!-- add maphilight plugin -->
<script type="text/javascript"
src="Demo_imagemap_highlight_files/jquery_002.js"></script>
</head>
<body>
<div class="content">
<div class="map"
style='display: block; background: transparent
url("Demo_imagemap_highlight_files/blanketaphi.png")
repeat scroll 0% 0%; position: relative; padding: 0px; width: 1037px;
height: 557px;'>
<canvas width="1037" height="557" style="width: 1037px; height: 557px;
position: absolute; left: 0px; top: 0px; padding: 0px; border: 0px none;
opacity: 1;"></canvas>
<img style="opacity: 0; position: absolute; left: 0px; top: 0px; padding: 0px;
border: 0px none;" src="Demo_imagemap_highlight_files/blanketaphi.png"
alt="foo" class="map maphilighted" usemap="#demo" height="557" width="1037"
border="0" />
</div>
</div>
<map name="demo" id="demo"></map>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
var f = (function(){
var xhr = [];
var files = [ "test.txt"];
for (i = 0; i < 1; i++) {
(function (i){
xhr[i] = new XMLHttpRequest();
xhr[i].open("GET", files[i], true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
// get text contents
j=20000*i + 50000;
var coords = xhr[i].responseText.split("\n");
coords = coords.filter(Boolean) //prevents extra rect with 0 coords
coords.forEach(function(coord) {
var area = document.createElement("area");
var att = document.createAttribute("data-maphilight");
if (i == 0) { //green
att.value = '{"strokeColor":"000000","strokeWidth":2,' +
'"fillColor":"009900","fillOpacity":0.5}';
}
area.setAttributeNode(att);
area.id = "r"+j;
area.shape = "rect";
area.coords = coord.substring(10,coord.length).trim()
.replace(/ +/g,","); // replaces spaces in txt file with commas
area.href = "#";
area.alt = "r"+j;
// create overlay with first term in string
var div = document.createElement("div");
div.id ="overlayr"+j;
div.innerHTML = coord.substring(0,10);
div.style.display = "none";
//increase j
j++;
// get map element
document.getElementById("demo").appendChild(area);
document.getElementById("demo").appendChild(div);
});
$('.map').maphilight();
//display overlay ids by mousing over
var elementPositions = [];
var hoveredElements = [];
if($('#demo')) {
$('#demo area').each(function() {
var offset = $(this).offset();
var top = offset.top;
var left = offset.left;
var bottom = $(window).height() - top - $(this).height();
var right = $(window).width() - left - $(this).width();
elementPositions.push({
element: $(this),
top: top,
bottom: bottom,
left: left,
right: right
});
//alert(top + "," + left + "," + right + "," + bottom);
});
$("body").mousemove(function(e) {
hoveredElements = [];
var yPosition = e.pageX;
var xPosition = e.pageY;
for (var i = 0; i < elementPositions.length; i++) {
if (xPosition >= elementPositions[i].left &&
xPosition <= elementPositions[i].right &&
yPosition >= elementPositions[i].top &&
yPosition <= elementPositions[i].bottom) {
// The mouse is within the element's boundaries
$("#hovers").append(elementPositions[i].element);
}
}
for (var i = 0; i < hoveredElements.length; i++) {
// The element as a jQuery object
var elem = hoveredElements[i];
var id = hoveredElements[i].attr('id');
$('#overlay'+id).show();
}
});
};
}
};
xhr[i].send();
})(i);
}
})();
};
</script>
Why not just something like this:
var elementPositions = [];
var hoveredElements = [];
if($('#demo')) {
$('#demo area').each(function() {
var offset = $(this).offset();
var top = offset.top;
var left = offset.left;
var bottom = $(window).height() - top - $(this).height();
var right = $(window).width() - left - $(this).width();
elementPositions.push({ element: $(this), top: top, bottom: bottom, left: left, right: right });
//alert(top + "," + left + "," + right + "," + bottom);
});
$("body").mousemove(function(e) {
hoveredElements = [];
var yPosition = e.pageX;
var xPosition = e.pageY;
for (var i = 0; i < elementPositions.length; i++) {
if (xPosition >= elementPositions[i].left &&
xPosition <= elementPositions[i].right &&
yPosition >= elementPositions[i].top &&
yPosition <= elementPositions[i].bottom) {
// The mouse is within the element's boundaries
hoveredElements.push(elementPositions[i].element);
$("#hovers").append(elementPositions[i].element);
}
} //end of for loop over all elements
console.log(hoveredElements);
for (var i = 0; hoveredElements.length; i++)
{ //for loop over all hovered elements
// The element as a jQuery object
var elem = hoveredElements[i];
var id = hoveredElements[i].attr('id');
console.log(id);
$('#overlay'+id).show();
// Do stuff to that jQuery element:
//??? something like elem.show();
}
You've got a lot of stuff here that doesn't make sense to me but here's what I can gather so far.
Your areas need to be in a container called demo area. Not sure how the space in the ID works so in my case I switched it to demoarea. Also somewhere in the page, there has to be another element called demo for anything to even happen.
Once that's done, the script loads demoarea into the elementPositions array. Judging from your description that's not what you want to do, you probably want to load all the elements inside demoareainto the array. So the first change is
$('#demo area').each(function() {
Becomes
$('#demoarea').children().each(function() {
Now what becomes confusing to me is that this script for whatever reason decides that you need to have another element called hover so it can move the element out of demoarea into hover when you mouse over it. If that is what you want, then you can do your show trick with some simple CSS.
<div style="display:none" id="overlayr6064"> Example Overlay ID name </div>
Becomes
<div id="overlayr6064"> Example Overlay ID name </div>
And then you add:
<style>
#demoarea div {
display: none;
}
#hover div {
display: block;
}
</style>
Assuming that is not what you wanted, what #liamEgan did to add the elements to the hoveredElements array is good, but you have an infinite loop here
for (var i = 0; hoveredElements.length; i++)
it should be
for (var i = 0; i < hoveredElements.length; i++)
Then the rest works... except one last thing, you want to load these listeners to your script when the page loads in a document ready method.
So in all it looks a bit like:
//display overlay ids by mousing over (my map is called 'demo')
var elementPositions = [];
var hoveredElements = [];
if($('#demo')) {
$('#demoarea').children().each(function() {
var offset = $(this).offset();
var top = offset.top;
var left = offset.left;
var bottom = $(window).height() - top - $(this).height();
var right = $(window).width() - left - $(this).width();
elementPositions.push({ element: $(this), top: top, bottom: bottom, left: left, right: right });
});
console.log('After Scanning demoarea elementPositions looks like:')
console.log(elementPositions);
$(document).ready(function () {
$("body").mousemove(function(e) {
hoveredElements = [];
var yPosition = e.pageX;
var xPosition = e.pageY;
for (var i = 0; i < elementPositions.length; i++) {
if (xPosition >= elementPositions[i].left &&
xPosition <= elementPositions[i].right &&
yPosition >= elementPositions[i].top &&
yPosition <= elementPositions[i].bottom) {
// The mouse is within the element's boundaries
if (typeof elementPositions[i].element != "undefined") {
hoveredElements.push(elementPositions[i].element);
$("#hovers").append(elementPositions[i].element);
}
}
} //end of for loop over all elements
for (var i = 0; i < hoveredElements.length; i++) { //for loop over all hovered elements
// The element as a jQuery object
console.log(hoveredElements[i]);
if (typeof hoveredElements[i] != "undefined") {
var elem = hoveredElements[i];
var id = elem.attr('id');
$('#overlay'+id).show();
}
// Do stuff to that jQuery element:
//??? something like elem.show();
}
});
});
}
#demoarea {
border: 2px blue dotted;
}
/* Border added so I can see where to mouse over */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="demo">
<div id="demoarea">
<area shape="rect" coords="431,499,458,491" href="#" id="r6064" alt="r6064">
<div style="display:none" id="overlayr6064"> Example Overlay ID name </div>
</div>
<div id="hovers">
</div>
</div>
Edit: sorry I added the undefined tests while fixing this because of the infinite loop but I think they're not really needed. Still nice to have though. Also since the area also gets moved into the hover area this script does try to show an element called overlayoverlayr6064r6064 which fortunately doesn't exist. But ya, again, probably not what you had in mind.
Related
I've run into a problem with running a loop to trigger a mousemove event on my HTML/CSS.
I know I can go through and get every individual ID on the HTML tags to execute the code the way I want. But I know there is a better way to do it with a loop of some sort and use far less code.
The images should follow the mouse while moving over the div with class mycard. Any suggestions or ideas on how to get it working properly would be very much appreciated.
I've tried running a loop to add the classes to divs but had no luck.
var mouseHover = document.getElementById('moveHover');
window.onmousemove = function(e) {
var x = e.clientX;
var y = e.clientY;
mouseHover.style.top = (y + 20) + 'px';
mouseHover.style.left = (x + 20) + 'px';
};
.mycard span {
position: absolute;
display: none;
z-index: 99;
}
.mycard:hover span {
display: block;
position: fixed;
overflow: hidden;
}
.imgHover a {
position: relative;
}
.imgHover span {
position: absolute;
display: none;
z-index: 99;
}
.imgHover a:hover span {
display: block;
position: fixed;
overflow: hidden;
}
<div class="imgHover mycard">
<div class="cardcost">
<p class="cardcosttext">2</p>
</div>
<div class="hscardepic">
<a style="margin-left: 1000%;vertical-align: middle;">
Doomsayer
<span id="moveHover">
<img src="Classic_Set/doomsayer.png" height="300" width="300" />
</span>
</a>
</div>
<div class="cardamount">
<p class="cardamounttext">×2</p>
</div>
</div>
If I understand what you're asking, you could use querySelectorAll to get the elements and forEach to move them:
// get the div that responds to mouse movement
const mycard = document.querySelector('.mycard');
// add a mousemove listener
mycard.addEventListener('mousemove', function(e) {
// get the DOM element with the mousemove listener from the event
const {target} = e;
// get img child elements of the target.
// (use whatever css selector you need here. doesn't have to img)
const images = target.querySelectorAll('img');
// iterate over each item...
images.forEach(image => {
// ...and do whatever you need to do with it
const x = e.clientX;
const y = e.clientY;
image.style.top = (y + 20) + 'px';
image.style.left = (x + 20) + 'px';
})
});
I'm also not entirely sure what your end-goal is, but I'll take a stab at it.
I would recommend changing moveHover to being the class instead of the ID. Then you could do something like this:
var mouseHover = null;
window.onmousemove = function (e) {
if(mouseHover != null){
var x = e.clientX;
var y = e.clientY;
mouseHover.style.top = (y+20) + 'px';
mouseHover.style.left = (x+20) + 'px';
}
};
function onHover(e){
mouseHover = e.target.querySelector('.moveHover');
}
var elements = document.getElementsByClassName('imgHover');
for(var i = 0; i < elements.length; i++){
elements[i].onmouseenter = onHover;
}
The loop runs one time to set the onmouseenter event. Sure beats moving all .moveHover elements all the time.
I'm trying to implement a text fade in on scroll similar to this https://codepen.io/hollart13/post/fade-in-on-scroll.
$(function(){ // $(document).ready shorthand
$('.monster').fadeIn('slow');
});
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},1500);
}
});
});
});
However, I do not want to use JQuery. I want to accomplish this using plain JavaScript. Unfortunately, most of the examples online are JQuery based and there's very little with plain JavaScript.
This is what I've attempted so far to "translate" this JQuery into plain JS. It's not working. Could anyone point at where I went wrong?
window.onscroll = function() {myFunction()};
function myFunction() {
var elements = document.getElementsByClassName("target");
for(var i = 0; i < elements.length; i++){
var bottomOfObject = elements[i].getBoundingClientRect().top +
window.outerHeight;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset :
(document.documentElement || document.body.parentNode ||
document.body).scrollTop;
var bottomOfWindow = scrollTop + window.innerHeight;
if(bottomOfWindow > bottomOfObject){
$(this).animate({'opacity': '1'}, 1500);
}
}
console.log(bottomOfObject);
}
Thanks in advance!
Try this simple vanilla JavaScript solution
var header = document.querySelector("#header");
window.onscroll = function() {
if (document.body.scrollTop > 50) {
header.className = "active";
} else {
header.className = "";
}
};
#header {
background-color: black;
transition: all 1s;
position: fixed;
height: 40px;
opacity: 0;
right: 0;
left: 0;
top: 0;
}
#header.active {
opacity: 1;
}
#wrapper {
height: 150vh;
}
<html>
<body>
<div id="header"></div>
<div id="wrapper"></div>
</body>
</html>
Essentially there is an element positioned on the top of the screen which is invisible at first (with opacity 0) and using javascript I add an class to it that makes it visible (opacity 1) what makes it slowly visible instead of instantly is the transition: all 1s;
Here's my version with dynamic opacity based on scroll position, I hope it helps
Window Vanilla Scroll
function scrollHandler( event ) {
var margin = 100;
var currentTop = document.body.scrollTop;
var header = document.querySelector(".header");
var headerHeight = header.getBoundingClientRect().height;
var pct = (currentTop - margin) / ( margin + headerHeight );
header.style.opacity = pct;
if( pct > 1) return false;
}
function addListeners() {
window.addEventListener('scroll' , scrollHandler );
document.getElementById("click" , function() {
window.scrollTop = 0;
});
}
addListeners();
EDIT: Ok, so I approached the problem the wrong way: to do what I intended to, I just needed to check if there was an overflow.
Here is the code (if it can help anyone):
<script type="text/javascript">
function textfit(){
var spans = document.body.getElementsByTagName("span");
for(var i = 0, l = spans.length; i < l; i++){
var span = spans[i];
var font = window.getComputedStyle(span, null).getPropertyValue('font-size');
var fontSize = parseInt(font);
do {
span.style.fontSize = (fontSize --) + "px";
} while (span.scrollHeight > span.clientHeight || span.scrollWidth > span.clientWidth);
}
}
$(document).ready(function() {
textfit();
});
</script>
OLD POST:
My problem is simple: I have a HTML page with a lot of span but not all of them have the same content. Regarding that, I want to adapt the fontsize of each content to fit perfectly its span; please note that I don't want to cut the textcontent, or add dots if it's too long, I just want to modify the fontSize.
JS:
function = textfit(){
var spans = document.body.getElementsByTagName("span");
for(var i = 0, l = spans.length; i < l; i++){
var maxHeight = spans[i].offsetHeight;
var maxWidth = spans[i].offsetWidth;
var textHeight = $(spans[i].textContent).height();
var textWidth = $(spans[i].textContent).width();
var fontSize = spans[i].style.fontSize;
do {
fontSize = fontSize - 1;
} while (textHeight > maxHeight || textWidth > maxWidth);
}
}
$(document).ready(function() {
textfit();
});
HTML/CSS:
<style>
span{
display: inline-block;
width: 100px;
height: 100px;
font-size: 20pt;
}
</style>
......
<body>
<div>
<span>SMALL</span>
<span>MEEEEEEEEEEEEEDIUM</span>
<span>HUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUGE</span>
</div>
</body>
As you may see, I'm using a "for" to run through every span and a "do...while" to adjust the font size of each of them.
My problems:
it looks like I'm not able to get the textcontent size (getting a "null" instead)
same thing with the fontsize (I'm getting an empty string)
Or maybe I'm approaching the problem the wrong way and I need to do it differently...
NB: JS are a little bit "new" for me so sorry if I did rookie mistakes
you are reseting a local variable by fontSize = fontSize - 1;, on a related note, textHeight and textWidth will not be update automatically by changing the fontsize, they are local variables.
On the other hand, you will need to wrap your texts in an additional element to be able to measure its dimensions.
<style>
.wrapper{
display: inline-block;
width: 100px;
height: 100px;
font-size: 20pt;
}
</style>
......
<body>
<div>
<span class='wrapper'><span>SMALL</span></span>
<span class='wrapper'><span>MEEEEEEEEEEEEEDIUM</span></span>
<span class='wrapper'><span>HUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUGE</span></span>
</div>
</body>
JS:
function = textfit(){
var spans = document.body.getElementsByClassName("wrapper");
for(var i = 0, l = spans.length; i < l; i++){
var span = spans[i];
var maxHeight = span.offsetHeight;
var maxWidth = span.offsetWidth;
var fontSize = parseInt(span.style.fontSize);
do {
var textHeight = span.firstChild.offsetHeight();
var textWidth = span.firstChild.offsetWidth();
span.style.fontSize = (fontSize --)+"pt";
} while (textHeight > maxHeight || textWidth > maxWidth);
//PS I suggest a binary-search-like algorithm to save time
}
}
$(document).ready(function() {
textfit();
});
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
This is a function thats supposed to move an image slowly to the right, it isnt working... what did i mess up?
<script type="text/javascript">
var userWidth = window.screen.width;
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left);
var tim = setTimeout("moveRight(id, speed)",50);
right = right+speed; // move
if (right > window.screen.height / 2)
{
right=0;
pp.style.left = right+"px";
}
}
</script>
Looks like id and speed aren't getting passed into moveRight(). When they're in the string as you have them they won't get evaluated. Have a look at this, it seems to do the trick. I stripped it down a little.
<div id="test" style="width: 50px; height: 50px; left: 0px; background-color: #000; position: absolute;"> </div>
<script type="text/javascript">
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left) || 0;
right += speed; // move
pp.style.left = right + "px";
var move = setTimeout(function() {
moveRight(id, speed);
}, 50);
}
moveRight('test', 1);
</script>
A jsfiddle to play with. You can tweak it to your liking.