Placing text over an image in JavaScript - javascript

I have the following code:
var MARKER_PATH = 'https://maps.gstatic.com/intl/en_us/mapfiles/marker_green';
var results_list = document.getElementById('list_results');
var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i);
var markerIcon = MARKER_PATH + markerLetter + '.png';
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 === 0 ? '#F0F0F0' : '#FFFFFF');
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = markerIcon;
icon.setAttribute('class', 'placeIcon');
icon.setAttribute('className', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results_list.appendChild(tr);
This MARKER_PATH only has alphabet letters which is not enough for 60 items as it goes from A - Z. I like to have numbers inside the markers. I can create 60 images and load them locally, but that would be over killed with all those images. Therefore,
I want to create only 1 image and place a numbers as a text over this image. How can I do this?

Just put a class on the td with css background pointing to the image icon, then iterate like this,(you can run this snippet I created):
var MARKER_PATH = 'https://maps.gstatic.com/intl/en_us/mapfiles/marker_green';
var results_list = document.getElementById('list_results');
var markerLetter = "";
var i;
for (i = 0; i < 60; i++) {
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 === 0 ? '#F0F0F0' : '#FFFFFF');
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
iconTd.setAttribute('class', 'mybackground');
var name = document.createElement('div');
name.innerHTML = 's'+i;
iconTd.innerHTML = ""+i;
nameTd.innerHTML = "Title "+i;
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results_list.appendChild(tr);
}
td.mybackground{
background-image: url(http://www.whitehousewhitetails.com/wp-content/uploads/2012/02/google_pin.png); /* forward slash for the path */
width: 25px; /* use you own image size; */
height: 46px; /* use you own image size; */
background-repeat: no-repeat;
background-position: left top;
text-align: center;
vertical-align: top;
font-size: 40px;
color:blue;
}
<table id="list_results" border="1">
<tr><td>img</td>
<td>description</td>
</tr>
</table>

Related

How to create a css grid with javascript with a variable number of "cells"?

I am trying to (in Javascript)
Style a div as a CSS Grid in which the number of rows and columns can change (dependent on a future prompt element).
Default this Grid to be 16x16 when the page first loads.
Create and append divs to this grid that will fill all the grid areas. e.g. in the 16x16 grid, there will be 256 created divs.
I tried to do this via a loop. As demonstrated below:
<div class = "grid"> </div>
.grid{
height: 70vh;
width: 80vw;
}
const gridContainer = document.getElementsByClassName("grid");
let rowtot = 16;
let celltot = rowno * rowno;
gridContainer.style.display = "grid";
gridContainer.style.gridTemplateRows = `repeat(${rowtot}, 1fr)`;
gridContainer.style.gridTemplateColumns = `repeat(${rowtot}, 1fr)`;
let row = 1;
let column = 1;
for(let i = 1; i <= celltot; i++){
let cell = document.createElement("div");
cell.style.border = "1px solid black";
cell.style.gridRow = row;
cell.style.gridColumn = column;
column +=1;
if (column == 16){
row += 1;
column = 1;
}
gridContainer.appendChild(cell);
}
Maybe that way ;)
let gridContainer = document.querySelector('.grid');
let rowtot = 16;
let celltot = rowtot * rowtot;
gridContainer.style.display = 'grid';
gridContainer.style.gridTemplateRows = `repeat(${rowtot}, 1fr)`;
gridContainer.style.gridTemplateColumns = `repeat(${rowtot}, 1fr)`;
let row = 1;
let column = 1;
for (let i = 1; i <= celltot; i++) {
let cell = document.createElement('div');
cell.style.border = '1px solid black';
cell.style.gridRow = row;
cell.style.gridColumn = column;
cell.textContent = i;
column += 1;
if (column === rowtot + 1) {
row += 1;
column = 1;
}
gridContainer.appendChild(cell);
}
.grid {
height: 70vh;
width: 80vw;
}
<div class="grid"> </div>

CSS Font-size to maintain same word width

I'm trying to get the words "Hello", "Projects", "Social" and "Contact" to responsively adjust their font-size so that the words are all the same width rather than having to go in pixel by pixel.
I thought I was on to something with using viewport width but that isn't having the effect I'm after.
See image for the desired effect.
You may adjust font-size and also letter-spacing using vw unit
.title {
font-size: 15vw;
padding: 20px 0;
font-family: arial;
}
.title:first-child {
letter-spacing:5vw;
}
<div>
<div class="title">
Hello
</div>
<div class="title">
Projects
</div>
</div>
You can use JavaScript to wrap each letter in a span. Then you can use flexbox to distribute the spans evenly inside the p.
The words in the example below are inside a div with a fixed width in px. You can use other units as you need - %, vw etc
Example
const words = document.querySelectorAll('.tracking');
for (let i = 0; i < words.length; i++) {
const text = words[i].textContent.split('');
words[i].innerHTML = '';
text.forEach((letter, index) => {
const span = document.createElement('span');
const textnode = document.createTextNode(letter);
span.appendChild(textnode);
words[i].appendChild(span);
});
}
div {
width: 150px;
margin: 0 auto;
}
.tracking {
margin: 0;
padding: .5rem;
font-family: sans-serif;
font-weight: bold;
text-transform: uppercase;
color: #FFF;
display: flex;
justify-content: space-between;
}
div div:nth-of-type(1) {
background: red;
}
div div:nth-of-type(2) {
background: orange;
}
div div:nth-of-type(3) {
background: lightgrey;
}
div div:nth-of-type(4) {
background: black;
}
<div>
<div>
<p class="tracking">Hello</p>
</div>
<div>
<p class="tracking">Projects</p>
</div>
<div>
<p class="tracking">Social</p>
</div>
<div>
<p class="tracking">Contact</p>
</div>
</div>
var d = document.getElementById("master");
// set your margin... depends from font style
 var margin= 2;
 function font(){
var lett = document.getElementById("master").clientWidth;
setInterval(function(){font()},0)}
function getCount(matchResult) {
return matchResult ? matchResult.length : 0;
}
function alert(){
var pm = document.getElementById("master").querySelectorAll('*');
var num ;
for (num = 0; num < pm.length; num++){
var str = pm[num].textContent;
var countA = getCount(str.match(/A/g));
var countB = getCount(str.match(/B/g));
var countC = getCount(str.match(/C/g));
var countD = getCount(str.match(/D/g));
var countE = getCount(str.match(/E/g));
var countF = getCount(str.match(/F/g));
var countG = getCount(str.match(/G/g));
var countH = getCount(str.match(/H/g));
var countI = getCount(str.match(/I/g));
var countJ = getCount(str.match(/J/g));
var countK = getCount(str.match(/K/g));
var countL = getCount(str.match(/L/g));
var countM = getCount(str.match(/M/g));
var countN = getCount(str.match(/N/g));
var countO = getCount(str.match(/O/g));
var countP = getCount(str.match(/P/g));
var countQ = getCount(str.match(/Q/g));
var countR = getCount(str.match(/R/g));
var countS = getCount(str.match(/S/g));
var countT = getCount(str.match(/T/g));
var countU = getCount(str.match(/U/g));
var countV = getCount(str.match(/V/g));
var countW = getCount(str.match(/W/g));
var countX = getCount(str.match(/X/g));
var countY = getCount(str.match(/Y/g));
var countZ = getCount(str.match(/Z/g));
var counta = getCount(str.match(/a/g));
var countb = getCount(str.match(/b/g));
var countc = getCount(str.match(/c/g));
var countd = getCount(str.match(/d/g));
var counte = getCount(str.match(/e/g));
var countf = getCount(str.match(/f/g));
var countg = getCount(str.match(/g/g));
var counth = getCount(str.match(/h/g));
var counti = getCount(str.match(/i/g));
var countj = getCount(str.match(/j/g));
var countk = getCount(str.match(/k/g));
var countl = getCount(str.match(/l/g));
var countm = getCount(str.match(/m/g));
var countn = getCount(str.match(/n/g));
var counto = getCount(str.match(/o/g));
var countp = getCount(str.match(/p/g));
var countq = getCount(str.match(/q/g));
var countr = getCount(str.match(/r/g));
var counts = getCount(str.match(/s/g));
var countt = getCount(str.match(/t/g));
var countu = getCount(str.match(/u/g));
var countv = getCount(str.match(/v/g));
var countw = getCount(str.match(/w/g));
var countx = getCount(str.match(/x/g));
var county = getCount(str.match(/y/g));
var countz = getCount(str.match(/z/g));
var countspace = getCount(str.match(/ /g));
var groupa = 22*(counti+countj+countl);
var groupb = 28*(countI+countf+countt);
var groupc = 33*(countr);
var groupd = 50*(countJ+countc+countk+counts+countv+countx+county+countz);
var groupe = 56*(countL+counta+countb+countd+counte+countg+counth+countn+counto+countp+countq+countu);
var groupf = 61*(countF+countT+countZ);
var groupg = 67*(countA+countB+countE+countK+countP+countS+countV+countX+countY);
var grouph = 72*(countC+countD+countH+countN+countR+countU+countw);
var groupi = 78*(countG+countO+countQ);
var groupj = 83*(countM+countm);
var groupk = 94*(countW);
var groupl = 28*(countspace);
var totalsize = (groupa+groupb+groupc+groupd+groupe+groupf+groupg+grouph+groupi+groupj+groupk+groupl)/100;
var lett = pm[num].clientWidth;
var final = Math.floor(lett / totalsize) ;
pm[num].style.fontSize=final-margin+"px";
}
setInterval(function(){alert()},0)
}
window.onload = function(){
font();
alert();
}
div {text-align:center;
width:350px;
margin:0px;
padding:0px;}
p{
background-color:gray;
margin:0px;
padding:0px;
color:white}
.orange{
background-color:orange;}
.red{
background-color:red;}
<body>
<div id="master">
<p>Text using font-master.js </p>
<p>How simply is that </p>
<p class="orange">Hello</p>
<p class="red">Project</p>
</div>
</body>
you can use my js. plug in it is easy and free to use:
https://github.com/foxreaper/font-master
Text will fit to your div or sreen size... If you will have any issue let me know.

Display single image multiple times in a table using JS

I have to make a game in which there is an 8x8 table and a coin displays on them(more than at 10 positions at a time) for 3000milliseconds on different position simultaneously. The coin display should start at a click of "Start" button and it continues for 1minute. My problem is that I am not able to make a random function which generates images randomly on different positions.it is giving some error of appendchild undefined.I want my image to display randomly on different positions),Here what I've tried so far.I've just started learning JS so please don't judge my code & i'm posting this again because i didn't get any response in my previous post.
I had "display:none;" all the coins and i want a random function at multiple positions on which the coins displays block.
PS:I can't use any Jquery and remove the mistakes done previously
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
var tr = tbl.getElementsByTagName("tr")[randomNumber];
var td = tbl.getElementsByTagName("td")[randomNumber];
var img = tbl.getElementById("coin_image");
td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
i don't know exactly what you are looking for but it may works using same id multiple times is not a good choice
<script type="text/javascript">
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image'+i+'">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
//var tr = tbl.getElementsByTagName("tr")[randomNumber];
//var td = tbl.getElementsByTagName("td")[randomNumber];
var img = document.getElementById("coin_image"+randomNumber+"");
//td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
I think I could tweak your code:
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.id = 'myTable';
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="http://icons.iconarchive.com/icons/awicons/vista-artistic/128/coin-icon.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.getElementById('myTable');
var randomNumber = Math.floor(Math.random() * 7);
var tr = Array.prototype.slice.call(tbl.getElementsByTagName("tr"))[randomNumber];
var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
var img = document.getElementById("coin_image");
td.appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
Your inaccuracies:
add an id to the table when you initially create it in function tableCreate() like tbl.id ='myTable';
variable tbl in onTimer() function shoudn't contain a new table but
rather the existing one like var tbl = document.getElementById('myTable');
functions like getElementsByTagName("tr") return HTMLCollections,
not arrays. To convert it into array use
Array.prototype.slice.call(tbl.getElementsByTagName("tr"))
If I am not mistaken, you can call getElementById only on
document, so it should be var img = document.getElementById("coin_image");, not var img =tbl.getElementById("coin_image");
td variable in onTimer's interval already contains the td
element, no need to add an index. So, it should be
td.appendChild(img);
In order to avoid placing all the coins in the same row, change var
td = Array.prototype.slice.call(tbl.getElementsByTagName("td"))[randomNumber];
to var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
It makes your code work, but there are some other, lets say, logical problems because the coins do not disappear from the cells. Also they only appear on cells with coordinates like (0,0) (2,2) (4,4) etc. because you generate the random number only once and then use it for both - row and column. I don't know maybe it is what you want. If not, work on it too.

addEventListerner("click",function) - text will get appended to a div - but this does not work the second time around

Onclick dynamically created elements get added to list, but on the second click it does not work.
document.getElementById("add-comment").addEventListener("click",function(){
createComments();
});
function createComments(){
//append the new edit to comment list
var storeDiv = document.createElement("DIV");
var outerDiv = document.createElement("DIV");
var att = document.createAttribute("class");
att.value = "user-avatar-thumbnail left-position";
outerDiv.setAttributeNode(att);
var avatarImg = document.createElement("IMG");
avatarImg.src ="../1.jpg";
outerDiv.appendChild(avatarImg);
var attImg = document.createAttribute("class");
attImg.value = "left-position";
avatarImg.setAttributeNode(attImg);
var altAttr = document.createAttribute("alt");
altAttr.value = "avatar-thumbnail";
avatarImg.setAttributeNode(altAttr);
outerDiv.appendChild(avatarImg);
var avatarName = document.createElement("H5");
var avatarNameContent = document.createTextNode("Added newly");
var attImg = document.createAttribute("class");
attImg.value = "left-position";
avatarName.setAttributeNode(attImg);
avatarName.appendChild(avatarNameContent);
outerDiv.appendChild(avatarName);
var textRegion = document.createElement("TEXTAREA");
var textId = document.createAttribute("id");
textId.value = "comment-area";
textRegion.setAttributeNode(textId);
outerDiv.appendChild(textRegion);
var postCommentButton = document.createElement("BUTTON");
var postCommentButtonValue = document.createTextNode("Post");
postCommentButton.appendChild(postCommentButtonValue);
var createIDPost = document.createAttribute("id");
createIDPost.value="post-comment";
postCommentButton.setAttributeNode(createIDPost);
postCommentButton.appendChild(postCommentButtonValue);
postCommentButton.addEventListener("click",function(){
var commentsGiven = textRegion.value;
if (commentsGiven.length < 1){
alert("please enter your comment");
}
else {
document.getElementById("comment-section").appendChild(outerDiv);
document.getElementById("comment-section").style.display = "block";
document.getElementById("enter-comments").style.display = "none";
outerDiv.removeChild(cancelCommentButton);
outerDiv.removeChild(postCommentButton);
var commentPara = document.createElement("P");
commentPara.innerHTML = commentsGiven;
var attrComment = document.createAttribute("class");
attrComment.value = "left-position DescriptionExcerpt";
commentPara.setAttributeNode(attrComment);
outerDiv.appendChild(commentPara);
outerDiv.removeChild(textRegion);
}
});
outerDiv.appendChild(postCommentButton);
var cancelCommentButton = document.createElement("A");
cancelCommentButton.href = "#";
var createIDCancel = document.createAttribute("id");
createIDCancel.value="cancel-comment";
cancelCommentButton.setAttributeNode(createIDCancel);
var cancelCommentButtonValue = document.createTextNode("Cancel");
cancelCommentButton.appendChild(cancelCommentButtonValue);
outerDiv.appendChild(cancelCommentButton);
document.getElementById("enter-comments").appendChild(outerDiv);
};
#enter-comments, #comment-section {
border: dotted 1px #bfbfbf;
padding: 10px;
margin-top: 10px;
}
.user-avatar-thumbnail p{
background-color:#bfbfbf;
padding: 5px;
}
<div class="icon-details add-comments clearfix">
Add Comment...
</div>
<div id="enter-comments">
</div>
<div id="comment-section">
</div>
Here when you click the add comment the first time and enter some text in the text box and click on post button, that text will get appended to a div, but this does not work the second time around.

Set a custom % of 1's into a 2D blank array, where the 1's are randomly shuffled?

I've been a long time lurker on Stack Overflow but I couldn't seem to find a suitable existing solution...
I'm learning JS and HTML, and I've been playing around with 2D arrays to make game board. So far I made a custom # of rows/columns for a game board with all white tiles (represented as 0 for now).
My goal is to use an input field for a % of black tiles (represented as 1) to fill up the board (2D Array), but the black tiles have to be randomly distributed/shuffled among it.
Here's what I've got so far..
https://jsfiddle.net/5pvm4mmy/6/
function generateArray() {
var myNode = document.getElementById("table");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
rows = $("#rows-field").val();
cols = $("#cols-field").val();
concentration = $("#concentration-field").val()
source = $("#source-field").val();
target = $("#target-field").val();
var table = document.getElementById("table");
for (var i = 0; i < rows; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < cols; j++) {
var td = document.createElement('td');
if (i%2 == j%2) {
td.className = "white";
} else {
td.className = "black";
}
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
Thanks in advance for any help or advice.
If you need a random selection of a predefined set of values, you can use a stack. Think of it as a deck of cards and you pick a random card each time from the number of card left in the deck. In this case you have only 2 values but you may want to set the number of black and white. For this you can use a pseudo stack.
var black = 29; // 29 blacks the rest white
var white = (rows * cols) - black;
function getRandSquare(){
var select = Math.floor(Math.random() * (black + white));
if(select > black){
white -= 1;
return "white";
}
black -= 1;
return "black";
}
If you have many options like a deck of cards you use an array.
Example of a random stack.
// create a deck
var cards = [];
for(var c = 0; c < 52; c++){
cards[c] = c;
}
function shuffle(cards){
var shuf = []; // to hold the shuffled deck
while(cards.length > 0){ // pick a random item, take it from the stack and
// put on the new stack until there are no items
// left
shuf.push(cards.splice(Math.floor(Math.random() * cards.length),1));
}
return shuf; // return shuffled deck
}
cards = shuffle(cards); // get shuffled deck.
Which will work for anything where you need to pick randomly from a predefined set. It only takes one pass and the set is as random as the random number generator
To show psuedo stack working ... Always has 60 black
var cont;
function draw(){
var rows = 15;
var cols = 15;
var black = 60; // 29 blacks the rest white
var white = (rows * cols) - black;
function getRandSquare(){
var select = Math.floor(Math.random() * (black + white));
if(select > black-1){
white -= 1;
return "white";
}
black -= 1;
return "black";
}
var bCount = 0;
cont = document.createElement("div");
for(var y = 0; y < rows; y++){
for(var x = 0; x < cols; x++){
var s = document.createElement("span");
s.className = getRandSquare();
if(s.className === "black"){
s.textContent = bCount;
bCount += 1;
}
s.style.top = ((y+2) * 20) + "px";
s.style.left = (x * 20) + "px";
s.style.width = "20px";
s.style.height = "20px";
cont.appendChild(s);
}
}
document.body.appendChild(cont);
}
document.body.onclick = function(){
document.body.removeChild(cont);
cont = null;
draw();
}
draw();
span {
position:absolute;
border : 1px solid;
font-size : small;
text-align : center;
}
.black {
background : black;
border-color :white;
color : white;
}
.white {
background : white;
border-color :black;
}
<h3>Click to randomise</h3>
Never mind. I got it done, thanks!
https://jsfiddle.net/5pvm4mmy/8/
function generateArray() {
var myNode = document.getElementById("table");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
rows = $("#rows-field").val();
cols = $("#cols-field").val();
concentration = $("#concentration-field").val();
source = $("#source-field").val();
target = $("#target-field").val();
var table = document.getElementById("table");
for (var i = 0; i < rows; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < cols; j++) {
var td = document.createElement('td');
if (concentration < Math.floor((Math.random() * 100) + 1)) {
td.className = "white";
} else {
td.className = "black";
}
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}

Categories

Resources