Filling CSS grid with JavaScript - javascript

I am working on a personal project with a canvas that is a CSS grid. It is 17 rows and columns and instead of adding 289 divs manually, that I would create a for loop to do it for me when the page loads.
JavaScript:
var row = 1;
var column = 1;
function init() {
for (var i = 0; i < 289; i++) {
var div = document.createElement("div");
div.style.color = "gray";
div.style.gridRow = row;
div.style.gridColumn = column;
column += 1;
if (column == 17) {
row += 1;
column = 0;
}
console.log("test");
}
}
HTML:
<body onLoad="init();">
<canvas id="myCanvas" width="600" height="600"></canvas>
</body>
This is the only 'version' that I've tried that doesn't spit an error at me, but still nothing shows up. It runs though, because the console displays "test".
I've tried replacing:
var div = document.createElement("div");
with
var div = document.canvas.createElement("div");`,
var div = document.myCanvas.createElement("div");
...etc. (which probably aren't the right syntax but I tried them anyway) and it gives me this error when evaluating document.myCanvas.createElement:
TypeError: undefined is not an object
Basically I just want each grid box in the canvas to be filled using JS when the page loads. Also, I'm very new to programming so simple terms are much appreciated. Thank you in advance.

I ended up creating a div that had the canvas inside it and replacing:
var div = document.createElement("div");
with:
var newDiv = document.createElement("div");
document.getElementById("background").appendChild(newDiv);
and it worked great.

Related

output specific data from div and print it via printer

I've spent all day in getting a solution for my need but since i'm not an experienced coder it's time for me to ask you guys for a little help.
My scenario is:
I have some php code like:
<div id="unique_name">
<?php function_show_qrcode()?>
<?php function_show_text1()?>
<?php function_show_text2()?>
<?php function_show_text3()?>
</div>
What i want to achieve is to print the content of "unique_name" div (qrcode and some additional info) directly to a label printer attached via wireless on my smartphone and PC, printer that prints on continuous paper with a width of 62mm.
I have tried a lot of codes that i found but with no success because of browsers behavior regarding window.print()
The following code is working on firefox and chrome on pc but it is not working on safari mobile
<script>
function printDiv(unique_name) {
var printContents = document.getElementById(unique_name).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
Print label
I am stuck on that and i think that something like converting the content of unique_name div into an image, save it and print it after that should work but there are a lot of steps to do and we want to do it more easy something like click and print or click and popup and then print and the most important thing is that it needs to work on mobile browsers
Thank you in advance!
try this :
<script>
function printDiv(myId){
var HiddenElements = document.querySelectorAll( 'body *' ); // get all the elements in the body
var VisibleElements = document.querySelectorAll( '#' + myId + ' *' ); // gets the elements inside the div to be printed
var index = 0, length = HiddenElements.length;
for ( ; index < length; index++) {
HiddenElements[index].style.visibility = "hidden"; // hide all the elements in the body
}
index = 0;
length = VisibleElements.length;
for ( ; index < length; index++) {
VisibleElements[index].style.visibility = "visible"; // show all the elements inside the div to be printed
}
// display the element to be printed
myElement = document.getElementById(myId);
myElement.style.visibility = "visible"
var oldPos = myElement.style.position;
myElement.style.position = "absolute";
myElement.style.left = 0;
myElement.style.top = 0;
setTimeout(window.print, 1000); // Wait a bit for the DOM then Print ( Safari :/ )
// wait for the data to be sent to the printer then display the previous content
setTimeout(function(){
index = 0;
length = HiddenElements.length;
for ( ; index < length; index++) {
HiddenElements[index].style.visibility = "visible";
}
myElement.style.position = oldPos;
}, 5000);
}
</script>
Print label
JsFiddle : https://jsfiddle.net/2m5ha1ta/67/
i don't know why on JsFiddle the onclick doesn't work, so i added an id to the a and added an eventListener to it and it's working ( check the fiddle )
i don't know why exactly but apparently in Safari , Window.print is executed before the DOM is manipulated,
try putting the window.print() in a timeout:
replace this line window.print(); with setTimeout(window.print, 1000);
give it some time to print, then put back the original content :)
setTimeout(function(){
document.body.innerHTML = originalContents;
}, 2000)
you can play with the timeout's number of milliseconds until you get the sweet spot, it doesn't have to be 2000.

Appending to body with javascript

I have an assignment to make several bugs fly around the screen randomly, but I'm having problems getting divs to be added to the html body through javascript.
<head>
<title>Fly little bug! Fly!</title>
<script type="text/javascript">
/* <![CDATA[ */
var numBugs = 0;
var body = document.getElementsByTagName("body");
function bug(startX, startY, xSpeed, ySpeed){
var self = this;
this.xPos = startX;
this.yPos = startY;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.divId = "bug" + numBugs;
this.div = document.createElement("div");
this.div.innerHTML = "test";
body.appendChild(self.div);
this.fly = function(){
self.xPos += self.xSpeed;
self.yPos += self.ySpeed;
}
this.fly();
this.flyInterval = setInterval(function(){ self.fly(); },5000);
numBugs++;
}
/* ]]> */
</script>
</head>
<body onload = "var bug1 = new bug(10, 20, 5, 3);">
</body>
</html>
I can see two problems.
The getElementsByTagName function returns an array of elements. You have to be explicit that you want the first element of the array.
var body = document.getElementsByTagName("body")[0];
You're essentially saying "give me all the tags in the document of type 'body'". It gives you a list of tags, and you have to get the first one even though there should only be one "body" in any HTML document. The [0] in the code above gives you the first one.
You are trying to access the body before it's created. The <script> occurs in the document before the <body> tag, so at the time the script is executed, the body doesn't exist. You need to move the call to getElementsByTagName inside the bug() function.
document.body.innerHTML += '<div>Div Content</div>';
Look into jQuery if you want to make simple DOM manipulation easier on yourself.

Getting images to change in a for loop in javascript

So far I created an array with 11 images, initialized the counter, created a function, created a for loop but here is where I get lost. I looked at examples and tutorial on the internet and I can see the code is seeming simple but I'm not getting something basic here. I don't actually understand how to call the index for the images. Any suggestions. Here is the code.
<script type="text/javascript">
var hammer=new Array("jackhammer0.gif",
"jackhammer1.gif",
"jackhammer2.gif",
"jackhammer3.gif",
"jackhammer4.gif",
"jackhammer5.gif",
"jackhammer6.gif",
"jackhammer7.gif",
"jackhammer8.gif",
"jackhammer9.gif",
"jackhammer10.gif")
var curHammer=0;
var numImg = 11;
function getHammer() {
for (i = 0; i < hammer.length; i++)
{
if (curHammer < hammer.length - 1) {
curHammer = curHammer +1;
hammer[i] = new Image();
hammer[i].src="poses/jackhammer" +(i+1) + ".gif";
var nextHammer = curHammer + 1;
nextHammer=0;
{
}
}
}
}
setTimeout("getHammer()", 5000);
</script>
</head>
<body onload = "getHammer()";>
<img id="jack" name="jack" src = "poses/jackhammer0.gif" width= "100" height ="113" alt = "Man and Jackhammer" /><br/>
<button id="jack" name="jack" onclick="getHammer()">Press button</button>
Following on what Paul, said, here's an example of what should work:
var hammer=["jackhammer0.gif","jackhammer1.gif","jackhammer2.gif","jackhammer3.gif",
"jackhammer4.gif","jackhammer5.gif","jackhammer6.gif","jackhammer7.gif",
"jackhammer8.gif","jackhammer9.gif","jackhammer10.gif"];
var curHammer=0;
function getHammer() {
if (curHammer < hammer.length) {
document.getElementById("jack").src= "poses/" + hammer[curHammer];
curHammer = curHammer + 1;
}
}
setTimeout("getHammer()", 5000);
The big missing element is that you need to call getElementById("jack") to get a reference to the DOM Image so that you can change it's source. If you're using jQuery or most other JS frameworks, just type $("#jack") to accomplish the same.
I don't understand the need for the for loop at all, just increment the index value [curHammer] each time you click, and reset if it passes your max index length (in this case 11).
Pseudo-Code:
currentHammer = -1
hammers = [ "a1.jpg", "a2.jpg", "a3.jpg"]
getHammer()
{
currentHammer = currentHammer + 1;
if(currentHammer > 2)
currentHammer = 0;
image.src = hammers[currentHammer];
}
a) are you just trying to show an animated gif? If so, why not use Adobe's Fireworks and merge all those gifs into a single gif?
b) you know that the way you have it the display is going to go crazy overwriting the gif in a circle right?
c) you might want to put a delay (or not). If so, make the load new gif a separate function and set a timeout to it (or an interval).
Also, you are being redundant. How about just changing the src for the image being displayed?:
var jackHammer = new Array();
for (var i=0;i<11;i++) { //pre-loading the images
jackHammer[i] = new image();
jackHammer[i].src = '/poses/jackHammer'+i.toString()+'.gif';
} //remember that "poses" without the "/" will only work if that folder is under the current called page.
for (var i=0;i<11;i++) { //updating the image on
document.getElementById('jhPoses').src = jackHammer[i].src;
}
on the document itself,
< img id='jhPoses' src='1-pixel-transparent.gif' width='x' height='y' alt='poses' border='0' />

Javascript to Remove Elements loaded in iFrame

After searching Google and Stack Overflow I decided to ask if this is even possible.
Currently I am loading an iFrame on my site. I wish to hide a certain element loaded in the iFrame.
<span id="blahblah">
function collapseAll(){
var body = document.getElementById('body');
var spans = body.getElementsByTagName("span");
var span;
for (i = 0; i < spans.length; i++){
span = spans[i];
if(span.class=='blahblah'){
span.style.visibility = "hidden";
}
}
}
However this did not work. Question number one is can this be done? If yes could you explain how?
Thank you kindly.
You'll have to put that script inside the contents of the iframe. You can't access the DOM of another frame, especially if it's from another domain.
Sorry, but you cannot access elements within an iframe from the outer window, due to security controls.
You would have to try this, but you might be able to create a function on the window object of the iframe and the call it from the outer window.
In the iframe:
<script type="text/javascript">
window.collapseAll = function() {
.....
}
</script>
In the outer window:
<script type="text/javascript">
function doCollapse() {
document.getElementById('my_iframe").window.collapseAll();
}
</script>
Again, that's untested but I'm pretty sure Facebook does something similar to that.
if the iframe is from the same domain as your javascript is from then this is doable.
using plain javascript you would write the following
`
function collapseAll(){
var body = document.getElementById('body');
var spans = body.getElementsByTagName("span");
var span;
for (i = 0; i < spans.length; i++){
span = spans[i];
if(span.class=='blahblah'){
**span.style.display = "none";**
}
}
}
this fixes the issue.
if the iframe is from a different site (domain) then things would get really difficult..
there are solutions like greasemonkey which can operate on pages from different domains.
you can try
document.frame.document.getElementsByTagName('span')
<script type="text/javascript">
function remove_elemment() {
var body = document.getElementById('body');
var divs = body.getElementsByTagName("div");
var div;
for (i = 0; i < divs.length; i++){
div = divs[i];
if(div.class=='buybox'){
**div.style.display = "none";**
}
}
};
function doRemove() {
document.frame.document.getElementById('my_iframe').remove_elemment();
}();
</script>
<div class="floating-widget">
<iframe id="my_iframe" src="http://www.nodebeginner.org/index-vi.html" frameborder="0" width="100%" height="500">
</iframe>
</div>

How to change content of a div

I know this question has been asked before, but if someone could explain in greater detail it would be awesome. I have a div and a table and an image inside this div. I am making a image gallery, so I have two links forward and back, how do I make these links change the image, or rather all the content inside the div. I am very new to javascript, actually I know nothing at all about it, if I could get a step by step instruction that would be awesome, I have tried so of the other post codes but can not get it to work, so I have no idea what I am doing wrong.
Sample HTML:
<html>
<head><title>Dummy page</title></head>
<body>
<div id="divID">
<img id="backImg" src="http://test.com/sample.jpg">
</div>
</body>
</html>
To change the whole div:
var div = document.getElementByID('divID');
div.innerHTML = "<b>This is some html</b>";
To just change the image:
var img = document.getElementByID('backImg');
img.src = "http://www.host.com/image.jpg';
Here's a good example that I made that might help. Try it out -- http://jsfiddle.net/SuperBoi45/XMSGe/
Here's the code for a quick look:
HTML:
<button id="before">Previous</button>
<button id="next">Next</button>
<div id="imageGallery"></div>
JavaScript:
function $(id) {
return document.getElementById(id);
}
var foward = null,
back = null,
images = [
"http://www.toxel.com/wp-content/uploads/2009/04/conceptcar04.jpg",
"http://politicolnews.com/wp-content/uploads/2010/01/bill-gates-car.jpg",
"http://www.youthedesigner.com/wp-content/uploads/2008/05/car-wallpapers19.jpg",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-555c9ae9cfd364db5307b2e8d717a00d",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-01589fb639efec5433a3e30a8a8dd449",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-31f8cbd6627edc1ba9ef2828f3423fdf",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-0f47a0c2db85b5d7c134d41bcdc65b2e",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-739fd589778207e542a6e31873a24433",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-6056a5df58462ea4951a2b328243b7a2",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-59028363fc0f7d0ee7aa1ebc5e72713a",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-eb09864be7a1fbe7e821bc1ee08c3a8b",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-50bd88090e05a452bba67d510ba4a0cc",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-191b37eea296e90a242d24db90824c5c"
];
var img = new Image();
for (var i = 0; i < images.length; i++) { // caching the images for performance boost
img.src = images[i];
}
var image = {
count: -1,
next: function() {
if (image.count == (images.length) - 1) return false;
image.count += 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
},
previous: function() {
if (image.count <= 0) return false;
image.count -= 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
}
};
foward = image.next;
back = image.previous;
$('next').addEventListener("click", foward);
$('before').addEventListener("click", back);
The best thing about this is that all you have to do is add a new image URL to the array and it will still work.
If you want to change the images but not all the content in the div, I'd recommend putting in another div outside the image gallery.

Categories

Resources