I have the following code on my page:
$('#Report').click(Report);
function Report() {
var e = encodeURIComponent,
arr = [
"dataSource=" + e($('#DataSource').val()),
"statusID=" + e($('#StatusID').val())
];
window.location.href = '/Administration/Tests/Report?' + arr.join("&");
return false;
}
When a user clicks on the button with Id=Report then the function is called and it shows a page with report information.
However if the dataSource and statusID are not set then my code ends in an exception.
Is there some way I can check for the value of DataSource not being equal to "00" and StatusID not being equal to "0" and then show a dialog box telling the user these fields should be selected.
Ideally I would like to have something like the dialog box that Stackoverflow uses.
I'm not sure what 00 and 0 represent in your request, but I put them in there. I'm not familiar with that Stack Overflow dialog box, but here is some starting code to play with. The outer div (#error-frame) prevents clicking on any other elements while the box is displayed.
Demo: http://jsfiddle.net/ThinkingStiff/CW5wW/
Script:
function Report() {
var dataSource = $('#DataSource').val(),
statusId = $('#StatusID').val();
if( dataSource && statusId && dataSource != '00' && statusId != '0' ) {
var e = encodeURIComponent,
arr = [
"dataSource=" + e(dataSource),
"statusID=" + e(statusId)
];
window.location.href = '/Administration/Tests/Report?' + arr.join("&");
} else {
//error msg here, perhaps:
showError( 'Both Data Source and Status ID are required.' );
};
return false;
}
function showError( message ) {
document.getElementById( 'error-message' ).textContent = message;
document.getElementById( 'error-frame' ).style.display = 'block';
var error = document.getElementById( 'error' );
error.style.left = ( ( window.innerWidth / 2 ) - ( error.scrollWidth / 2 ) ) + 'px';
error.style.top = ( ( window.innerHeight / 2 ) - ( error.scrollHeight / 2 ) ) + 'px';
};
HTML:
<div id="error-frame"><div id="error"><div id="error-message"></div><button onclick="this.parentNode.parentNode.style.display='none'">OK</button></div></div>
CSS:
#error-frame {
display: none;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
z-index: 9999;
}
#error {
border: 4px solid darkgray;
height: 100px;
padding: 4px;
position: relative;
vwidth: 200px;
}
#error button {
position: absolute;
right: 0;
bottom: 0;
}
Related
how to make a stimulus (image, div, whichever's easiest) show up on right or left half of screen randomly using javascript.
Any ideas about having the button clicks record the reaction time, which button is clicked (left or right), and which side the stimulus was presented on?? Also, the left button should be "true" when stimulus is presented on the right and vice versa.
<head>
<style >
.divStyleLeft {
width: 300px;
height: 300px;
background-color: lightblue;
float: left;
}
.divStyleRight {
width: 300px;
height: 300px;
background-color: lightgreen;
float: right;
}
.maxWidth {
width: 100%;
}
.button {
float: right;
}
.button2 {
float: left;
}
</style>
</head>
<body onload="presentStimulus()">
<div class="button">
<button onclick="presentStimulus()">Click Me</button>
</div>
<div class="button2">
<button onclick="presentStimulus()">Click Me </button>
</div>
<div class="maxwidth"></div>
<div id="float" class="divStyleLeft" onclick="recordClick()">
I AM NOT FLOATING
</div>
<script>
let numClicks= 0;
let timeStart = 0;
let timeEnd = 0;
function Trial(trialTime, sidePresented,buttonClicked,) {
this.trialTime = trialTime;
this.sidePresented= sidePresented;
this.buttonClicked= buttonClicked;
}
let allTrials = [];
for(x = 0; x < 12; x++)
allTrials.push(new Trial(0,0,0));
Trial.prototype.toString=function(){
return this.trialTime + "ms, Side : " + this.sidePresented + ", Reaction Time: " + this.buttonClicked
+ "<br>";
};
function presentStimulus() {
const elem = document.querySelector ( '#float' );
const min = 1;
const max = 2;
const v = Math.floor(Math.random() * (max - min + 1)) + min;
console.log ( 'Random num is ' + v + ": ", '1 will go left, 2 will go right' );
v === 1 ?
( () => {
elem.classList = [ 'divStyleLeft' ];
elem.innerText = 'Hello!';
} ) () :
( () =>{
elem.classList = [ 'divStyleRight' ];
elem.innerText = 'Hi!';
} ) ();
}
function recordClick()
{
let theData = document.getElementById("#float").data;
timeEnd = Date.now();
allTrials[numClicks].trialTime = timeEnd - timeStart;
allTrials[numClicks].sidePresented = theData.sidePresented;
allTrials[numClicks].buttonClicked = theData.buttonClicked;
if (numClicks < 11) {
numClicks++;
presentStimulus();
}
else {
document.getElementById("float").style.visibility = "hidden";
let output = "";
for (x = 0; x < allTrials.length; x++)
output = output + "<b>:" + (x + 1) + "</b>:" + allTrials[x].toString();
document.getElementById("display").innerHTML = output;
}
}
</script>
<p id="display"></p>
</body>
There's a bunch of ways you could go about this.
If you're using plain 'ol JS, I'd probably create classes in CSS that float left or right, possibly appear as a flex container that displays left or right, whatever your specific need might be (again, there's a lot of ways to go about it, and one might be better than the other given your context).
When you've determined left or right (gen a random number or whatever), update the classlist on the DOM elements with the desired class to make it go this way or that.
For what it's worth, here's a bare-bones vanilla JS example. Again, I don't know your specific context, but this should give you a start on how to look at it. Floating may not be ideal, you may want to just hide/show containers that already exist on the left or right or actually create whole new DIVs and insert them into known "holder" containers (usually just empty divs), but the idea is the same; gen the random number, alter the classlists of the elements you want to hide/show/move/whatever, and if necessary, alter the innerHTML or text as needed.
<html>
<head>
<style>
.divStyleLeft {
width: 300px;
height: 300px;
background-color: lightblue;
float: left;
}
.divStyleRight {
width: 300px;
height: 300px;
background-color: lightgreen;
float: right;
}
.maxWidth {
width: 100%;
}
</style>
</head>
<body>
<button onclick="onClick()">Click Me</button>
<div class="maxwidth">
<div id="floater" class="divStyleLeft">
I AM NOT FLOATING
</div>
<div>
<script>
function onClick () {
const elem = document.querySelector ( '#floater' );
const min = 1;
const max = 2;
const v = Math.floor(Math.random() * (max - min + 1)) + min;
console.log ( 'Random num is ' + v + ": ", '1 will go left, 2 will go right' );
v === 1 ?
( () => {
elem.classList = [ 'divStyleLeft' ];
elem.innerText = 'I am floating LEFT';
} ) () :
( () =>{
elem.classList = [ 'divStyleRight' ];
elem.innerText = 'I am floating RIGHT';
} ) ();
}
</script>
</body>
</html>
I got a really great script found here : http://beeker.io/exit-intent-popup-script-tutorial
Here is the js (bioep.js) code :
window.bioEp = {
// Private variables
bgEl: {},
popupEl: {},
closeBtnEl: {},
shown: false,
overflowDefault: "visible",
transformDefault: "",
// Popup options
width: 400,
height: 220,
html: "",
css: "",
fonts: [],
delay: 1,
showOnDelay: false,
cookieExp: 1,
cookieManager: {
// Create a cookie
create: function(name, value, days) {
var expires = "";
if(days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
// Get the value of a cookie
get: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
// Delete a cookie
erase: function(name) {
this.create(name, "", -1);
}
},
// Handle the bioep_shown cookie
// If present and true, return true
// If not present or false, create and return false
checkCookie: function() {
// Handle cookie reset
if(this.cookieExp <= 0) {
this.cookieManager.erase("bioep_shown");
return false;
}
// If cookie is set to true
if(this.cookieManager.get("bioep_shown") == "true")
return true;
// Otherwise, create the cookie and return false
this.cookieManager.create("bioep_shown", "true", this.cookieExp);
return false;
},
// Add font stylesheets and CSS for the popup
addCSS: function() {
// Add font stylesheets
for(var i = 0; i < this.fonts.length; i++) {
var font = document.createElement("link");
font.href = this.fonts[i];
font.type = "text/css";
font.rel = "stylesheet";
document.head.appendChild(font);
}
// Base CSS styles for the popup
var css = document.createTextNode(
"#bio_ep_bg {display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: #000; opacity: 0.3; z-index: 10001;}" +
"#bio_ep {display: none; position: fixed; width: " + this.width + "px; height: " + this.height + "px; font-family: 'Titillium Web', sans-serif; font-size: 16px; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); -ms-transform: translateX(-50%) translateY(-50%); background-color: #fff; box-shadow: 0px 1px 4px 0 rgba(0,0,0,0.5); z-index: 10002;}" +
"#bio_ep_close {position: absolute; left: 100%; margin: -8px 0 0 -12px; width: 20px; height: 20px; color: #fff; font-size: 12px; font-weight: bold; text-align: center; border-radius: 50%; background-color: #5c5c5c; cursor: pointer;}" +
this.css
);
// Create the style element
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(css);
// Insert it before other existing style
// elements so user CSS isn't overwritten
document.head.insertBefore(style, document.getElementsByTagName("style")[0]);
},
// Add the popup to the page
addPopup: function() {
// Add the background div
this.bgEl = document.createElement("div");
this.bgEl.id = "bio_ep_bg";
document.body.appendChild(this.bgEl);
// Add the popup
if(document.getElementById("bio_ep"))
this.popupEl = document.getElementById("bio_ep");
else {
this.popupEl = document.createElement("div");
this.popupEl.id = "bio_ep";
this.popupEl.innerHTML = this.html;
document.body.appendChild(this.popupEl);
}
// Add the close button
this.closeBtnEl = document.createElement("div");
this.closeBtnEl.id = "bio_ep_close";
this.closeBtnEl.appendChild(document.createTextNode("X"));
this.popupEl.insertBefore(this.closeBtnEl, this.popupEl.firstChild);
},
// Show the popup
showPopup: function() {
if(this.shown) return;
this.bgEl.style.display = "block";
this.popupEl.style.display = "block";
// Handle scaling
this.scalePopup();
// Save body overflow value and hide scrollbars
this.overflowDefault = document.body.style.overflow;
document.body.style.overflow = "hidden";
this.shown = true;
},
// Hide the popup
hidePopup: function() {
this.bgEl.style.display = "none";
this.popupEl.style.display = "none";
// Set body overflow back to default to show scrollbars
document.body.style.overflow = this.overflowDefault;
},
// Handle scaling the popup
scalePopup: function() {
var margins = { width: 40, height: 40 };
var popupSize = { width: bioEp.popupEl.offsetWidth, height: bioEp.popupEl.offsetHeight };
var windowSize = { width: window.innerWidth, height: window.innerHeight };
var newSize = { width: 0, height: 0 };
var aspectRatio = popupSize.width / popupSize.height;
// First go by width, if the popup is larger than the window, scale it
if(popupSize.width > (windowSize.width - margins.width)) {
newSize.width = windowSize.width - margins.width;
newSize.height = newSize.width / aspectRatio;
// If the height is still too big, scale again
if(newSize.height > (windowSize.height - margins.height)) {
newSize.height = windowSize.height - margins.height;
newSize.width = newSize.height * aspectRatio;
}
}
// If width is fine, check for height
if(newSize.height === 0) {
if(popupSize.height > (windowSize.height - margins.height)) {
newSize.height = windowSize.height - margins.height;
newSize.width = newSize.height * aspectRatio;
}
}
// Set the scale amount
var scaleTo = newSize.width / popupSize.width;
// If the scale ratio is 0 or is going to enlarge (over 1) set it to 1
if(scaleTo <= 0 || scaleTo > 1) scaleTo = 1;
// Save current transform style
if(this.transformDefault === "")
this.transformDefault = window.getComputedStyle(this.popupEl, null).getPropertyValue("transform");
// Apply the scale transformation
this.popupEl.style.transform = this.transformDefault + " scale(" + scaleTo + ")";
},
// Event listener initialisation for all browsers
addEvent: function (obj, event, callback) {
if(obj.addEventListener)
obj.addEventListener(event, callback, false);
else if(obj.attachEvent)
obj.attachEvent("on" + event, callback);
},
// Load event listeners for the popup
loadEvents: function() {
// Track mouseout event on document
this.addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
// Reliable, works on mouse exiting window and user switching active program
if(!from || from.nodeName === "HTML")
bioEp.showPopup();
});
// Handle the popup close button
this.addEvent(this.closeBtnEl, "click", function() {
bioEp.hidePopup();
});
// Handle window resizing
this.addEvent(window, "resize", function() {
bioEp.scalePopup();
});
},
// Set user defined options for the popup
setOptions: function(opts) {
this.width = (typeof opts.width === 'undefined') ? this.width : opts.width;
this.height = (typeof opts.height === 'undefined') ? this.height : opts.height;
this.html = (typeof opts.html === 'undefined') ? this.html : opts.html;
this.css = (typeof opts.css === 'undefined') ? this.css : opts.css;
this.fonts = (typeof opts.fonts === 'undefined') ? this.fonts : opts.fonts;
this.delay = (typeof opts.delay === 'undefined') ? this.delay : opts.delay;
this.showOnDelay = (typeof opts.showOnDelay === 'undefined') ? this.showOnDelay : opts.showOnDelay;
this.cookieExp = (typeof opts.cookieExp === 'undefined') ? this.cookieExp : opts.cookieExp;
},
// Ensure the DOM has loaded
domReady: function(callback) {
(document.readyState === "interactive" || document.readyState === "complete") ? callback() : this.addEvent(document, "DOMContentLoaded", callback);
},
// Initialize
init: function(opts) {
// Handle options
if(typeof opts !== 'undefined')
this.setOptions(opts);
// Add CSS here to make sure user HTML is hidden regardless of cookie
this.addCSS();
// Once the DOM has fully loaded
this.domReady(function() {
// Handle the cookie
if(bioEp.checkCookie()) return;
// Add the popup
bioEp.addPopup();
// Load events
setTimeout(function() {
bioEp.loadEvents();
if(bioEp.showOnDelay)
bioEp.showPopup();
}, bioEp.delay * 1000);
});
}
}
And here is the HTML code:
<script type="text/javascript" src="bioep.js"></script>
<script type="text/javascript">
bioEp.init({
html: '<div id="#leaving-content">The content i want to print</div>',
css: '#leaving-content {padding: 5%;}'});
</script>
This script allow to open a pop-up when user try to leave the page. Pretty nice work. But i'm a great noob and for a personnal project i try to adapt this code to be able to run a pop-under with an another website inside an not only my own html code (like an iframe). Can you help me please ?
Thank you !
No need for such scripts if you only want it to work for the back button, here's some simple code to do the job (requires jQuery).
var popupWebsite = "http://seapip.com";
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './');
}
$(window).on('popstate', function() {
$("html").append("<iframe src="+popupWebsite +" style=\"position: fixed; top: 0; left: 0; width: 100%; height: 100%;\"></iframe>")
});
I have programmed a bit in JS, but found my projects to become really long and unnecessarily complex. I want to learn OOP JS, and find it much easier to learn when my code get pictured in colors and figures. Here is a little example program:
var box1Left1 = 0;
var box1Left2;
var box2Left1 = 0;
var box2Left2;
setInterval(box1Fly, 10);
function box1Fly() {
// Fly Right
if ( box1Left1 < 300 ) {
box1Left1++;
document.getElementById("box1").style.left = box1Left1 + "px";
box1Left2 = box1Left1;
}
// Fly Left
if ( box1Left1 >= (300) ) {
box1Left2--;
document.getElementById("box1").style.left = box1Left2 + "px";
}
// Fly Right Again
if( box1Left2 == 0 ) { box1Left1 = box1Left2; }
}
setInterval(box2Fly, 10);
function box2Fly() {
// Fly Right
if ( box2Left1 < 300 ) {
box2Left1++;
document.getElementById("box2").style.left = box2Left1 + "px";
box2Left2 = box2Left1;
}
// Fly Left
if ( box2Left1 >= (300) ) {
box2Left2--;
document.getElementById("box2").style.left = box2Left2 + "px";
}
// Fly Right Again
if( box2Left2 == 0 ) { box2Left1 = box2Left2; }
}
<div id="box1" style="position:absolute; top: 10px; left: 0px; width: 50px; height: 50px; background-color: #aa39fc;"></div>
<div id="box2" style="position:absolute; top: 100px; left: 0px; width: 50px; height: 50px; background-color: #2c79f1;"></div>
As you can see, simple things get quite messy! Here is the deal: Can I make only one function, some sort of general function, that can handle both of these two flying boxes at the same time? Instead of, as now, having two functions ( box1Fly & box2Fly ) that are almost duplicates?
Thank you very much, Best Regards!
Would feel happier if the downvoter says why the answer is downvoted and more than happy to edit the answer to make it alright. :)
Why can't you just pass a parameter, which takes in which id should it use? By the way, there's no OO JS in this.
var box1Left1 = 0;
var box1Left2;
var box2Left1 = 0;
var box2Left2;
setInterval('boxFly("box1")', 10);
setInterval('boxFly("box2")', 10);
function boxFly(box_id) {
// Fly Right
if ( box1Left1 < 300 ) {
box1Left1++;
document.getElementById(box_id).style.left = box1Left1 + "px";
box1Left2 = box1Left1;
}
// Fly Left
if ( box1Left1 >= (300) ) {
box1Left2--;
document.getElementById(box_id).style.left = box1Left2 + "px";
}
// Fly Right Again
if( box1Left2 == 0 ) { box1Left1 = box1Left2; }
}
<div id="box1" style="position:absolute; top: 10px; left: 0px; width: 50px; height: 50px; background-color: #aa39fc;"></div>
<div id="box2" style="position:absolute; top: 100px; left: 0px; width: 50px; height: 50px; background-color: #2c79f1;"></div>
To convert into Object Oriented JavaScript, use this:
var box1Left1 = 0;
var box1Left2;
var box2Left1 = 0;
var box2Left2;
var box = function (id) {
this.id = id;
this.fly = function () {
// Fly Right
if ( box1Left1 < 300 ) {
box1Left1++;
document.getElementById(id).style.left = box1Left1 + "px";
box1Left2 = box1Left1;
}
// Fly Left
if ( box1Left1 >= (300) ) {
box1Left2--;
document.getElementById(id).style.left = box1Left2 + "px";
}
// Fly Right Again
if( box1Left2 === 0 ) { box1Left1 = box1Left2; }
};
this.startFlying = function () {
console.log(id);
setInterval(this.fly, 10);
};
};
box1 = new box("box1");
box2 = new box("box2");
box1.startFlying();
box2.startFlying();
<div id="box1" style="position:absolute; top: 10px; left: 0px; width: 50px; height: 50px; background-color: #aa39fc;"></div>
<div id="box2" style="position:absolute; top: 100px; left: 0px; width: 50px; height: 50px; background-color: #2c79f1;"></div>
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
my code lists items from an rss feed onto an html page. although, the java script is a little finicky. it won't read some xml feeds, usually the feeds containing list items over 25. I just need another set of eyes to take a look at the code and tell me if i'm missing something obvious.
.js file-----------------------------------------------
//XML CODE
var http_request = false;
var dataFileName = new Array();
dataFileName[1] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml";
//dataFileName[2] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/uk_news/magazine/rss.xml";
//dataFileName[3] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/business/rss.xml";
function getData(dataFileIndex) {
if (window.ActiveXObject) { //IE
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) { //other
http_request = new XMLHttpRequest();
} else {
alert("your browser does not support AJAX");
}
http_request.open("GET",dataFileName[dataFileIndex],true);
http_request.setRequestHeader("Cache-Control", "no-cache");
http_request.setRequestHeader("Pragma", "no-cache");
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
if (http_request.responseText != null) {
processRSS(http_request.responseXML);
} else {
alert("Failed to receive RSS file from the server - file not found.");
return false;
}
}
}
}
http_request.send(null);
}
function processRSS(rssxml) {
RSS = new RSS2Channel(rssxml);
outputData(RSS);
}
function RSS2Channel(rssxml) {
this.items = new Array();
var itemElements = rssxml.getElementsByTagName("item");
for (var i=0; i<itemElements.length; i++) {
Item = new RSS2Item(itemElements[i]);
this.items.push(Item);
}
}
function RSS2Item(itemxml) {
this.title;
this.link;
this.description;
this.pubDate;
this.guid;
var properties = new Array("title", "link", "description", "pubDate", "guid");
var tmpElement = null;
for (var i=0; i<properties.length; i++) {
tmpElement = itemxml.getElementsByTagName(properties[i])[0];
if (tmpElement != null) {
eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
}
}
}
function outputData(RSS) {
dataString = "";
for (var i=0; i<RSS.items.length; i++) {
dataString += "<div class='itemBlock'>";
newDate = new Date(RSS.items[i].pubDate);
dateString = (newDate.getMonth()+1) + "/" + newDate.getDate() + "/" + newDate.getFullYear();
dataString += "<div class='itemDate'>" + dateString + "</div>";
dataString += "<div class='itemTitle'><a href='" + RSS.items[i].link + "' target='afps_news'>" + RSS.items[i].title + "</a></div>";
//dataString += "<div class='itemDescription'>" + RSS.items[i].description + "</div>";
dataString += "</div>";
}
document.getElementById('outputBlock').innerHTML = dataString;
}
//SCROLL BAR CODE
var ie=document.all;
var nn6=document.getElementById&&!document.all;
var isdrag=false;
var x,y;
var dobj;
var scrollPercent;
var boxTop;
var maxHeight;
var toppoint;
function movemouse(e) {
if (isdrag) {
//dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
toppoint = (nn6) ? ty + e.clientY - y : ty + event.clientY - y;
boxTop = parseInt(document.getElementById('scrollBarBox').style.top) - scrollBarBoxOffset;
if (toppoint < boxTop) toppoint = boxTop;
boxHeight = parseInt(document.getElementById('scrollBarBox').style.height);
maxHeight = boxTop + boxHeight - parseInt(document.getElementById('scrollBar').style.height);
if (toppoint > maxHeight) toppoint = maxHeight;
dobj.style.top = toppoint + "px";
scrollPercent = toppoint / maxHeight;
document.getElementById('textWindow').style.top = parseInt(0 - (document.getElementById('textWindow').offsetHeight - parseInt(document.getElementById('scrollBarBox').style.height)) * scrollPercent );
return false;
}
}
function selectmouse(e) {
var fobj = nn6 ? e.target : event.srcElement;
var topelement = nn6 ? "HTML" : "BODY";
while (fobj.tagName != topelement && fobj.className != "dragme") {
fobj = nn6 ? fobj.parentNode : fobj.parentElement;
}
if (fobj.className == "dragme") {
isdrag = true;
dobj = fobj;
//tx = parseInt(dobj.style.left + 0);
ty = parseInt(dobj.style.top + 0);
//x = nn6 ? e.clientX : event.clientX;
y = nn6 ? e.clientY : event.clientY;
document.onmousemove = movemouse;
return false;
}
}
document.onmousedown = selectmouse;
document.onmouseup = new Function("isdrag=false;");
html file-------------------------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>TEST</TITLE>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<SCRIPT src="script1.js"></SCRIPT>
<STYLE>BODY {
MARGIN: 0px; FONT: 8pt arial
}
#widgetBody {
BACKGROUND-Color:gray; WIDTH: 240px; POSITION: relative; HEIGHT: 299px
}
#textWindowBox {
LEFT: 63px; OVERFLOW: hidden; WIDTH: 152px; POSITION: absolute; TOP: 70px; HEIGHT: 221px
}
#textWindow {
PADDING-TOP: 7px; POSITION: relative
}
#scrollBarBox {
LEFT: 221px; WIDTH: 12px; POSITION: absolute; TOP: 74px; HEIGHT: 216px
}
#scrollBar {
BACKGROUND: url(images/widget_scroll-handle1.gif) no-repeat; WIDTH: 12px; POSITION: relative; HEIGHT: 40px
}
#defenseLinkLink {
LEFT: 4px; WIDTH: 20px; CURSOR: pointer; POSITION: absolute; TOP: 155px; HEIGHT: 140px; BACKGROUND-COLOR: transparent
}
#defenseLinkLink A {
DISPLAY: block; WIDTH: 20px; HEIGHT: 140px
}
.dragme {
POSITION: relative
}
.itemBlock {
PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 4px; MARGIN: 0px 0px 3px; PADDING-TOP: 0px; BORDER-BOTTOM: #adafb3 1px dotted
}
.itemDate {
FONT-SIZE: 0.9em; COLOR: #666; LINE-HEIGHT: 1.1em
}
.itemTitle {
FONT-WEIGHT: bold; LINE-HEIGHT: 1.1em
}
.itemTitle A {
COLOR: #254a7d; TEXT-DECORATION: none
}
.itemDescription {
}
</STYLE>
<SCRIPT>
var scrollBarBoxOffset = 74;
function init() {
document.getElementById('scrollBarBox').style.top = "74px";
document.getElementById('scrollBarBox').style.height = "216px";
document.getElementById('scrollBar').style.height = "40px";
}
</SCRIPT>
<META content="MSHTML 6.00.6001.18294" name=GENERATOR></HEAD>
<BODY onload=init()>
<DIV id=widgetBody>
<DIV id=textWindowBox>
<DIV id=textWindow>
<DIV id=outputBlock></DIV></DIV></DIV>
<DIV id=scrollBarBox>
<DIV class=dragme id=scrollBar></DIV></DIV>
<DIV style="CLEAR: both"></DIV></DIV>
<SCRIPT language=javaScript>getData(2)</SCRIPT>
</BODY></HTML>
Ok, got it working.
2 issues.
army.mil does not resolve! Please use "www.army.mil" instead.
IN RSS2Item replace this line:
if (tmpElement != null) {
with this:
if (tmpElement != null && tmpElement.childNodes[0]) {
Oh man, why are you using XMLHttpRequest directly? Use a library for that, and make your life easier :)
You could be running into cross-site scripting security problems. If the RSS feeds exist on a different domain than the page running the JavaScript, the browser will not let your JavaScript make the requests.
dataFileName[1] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml";
Unless you are (a) a script running from the BBC, or (b) a browser extension, you cannot make an XMLHttpRequest to that server.
dataString += "<div class='itemTitle'><a href='" + RSS.items[i].link
HTML/script injection. If you insist on rolling innerHTML instead of using simple DOM methods you must do HTML escaping to turn <&" into <&".
eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
Don't use eval, except in the very few unusual cases you need it. This isn't one of them; you can access a JavaScript property by name using:
this[properties[i]]= tmpElement.firstChild.data;
Also, and this is probably where the unreliability is coming in, you can't be sure there will be a single child Text node. If there is no content in that element, firstChild/childNodes[0] will not exist and you will get an exception. If there is complex content in the element (which normally there shouldn't be, but for RSS 0.9 there can be as unencoded HTML), firstChild.nodeValue won't contain the text content of the element. Instead you would have to walk over the Text node descendents gathering their nodeValue/data.