I'm trying to use document.getElementByClassId().style.color to change the color of an element in my HTML document. I can see that it does add an inline style tag to the element but they are seemingly ignored by the browser.
I tried using the !important tag but that changed nothing. Here is my HTML document. I changed my CSS for the elements I want to modify into inline tags but they are ignored as well. Everything else works so far.
Here is my code (I'm a beginner please go easy on me :/).
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel">';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.color = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
You have to style the backgroundColor instead of color, because the cells don't contain any text, to which the color would be applied to
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel"></td>';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.backgroundColor = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am working on a project where I have several hundred spans next to each other, with a letter of the text in each span. When I hover over one of the spans, I want to hide it, as well as the other spans nearby.
It makes an image like this:
##############
##############
##############
##############
My goal is to hide all of the spans in a given distance away from the mouse, like this:
HTML
<span id="overlay-1">#</span>
<!-- ... -->
<span id="overlay-142">#</span>
<span id="overlay-143">#</span>
I'm able to hide 1 of the spans by calling their ids on mouseover and changing the style to display=none, but I want to hide all that are in close proximity to the mouse. Any ideas on what I should do?
I tried to solve this through JS. Here is my code:
function paint() {
let txt = "";
for (let j = 0; j < 100; j++) {
txt += "<div>"
for (let i = 0; i < 100; i++) {
txt += `<span onmouseout="hoverOut()" onmouseover="hover(this)" onmouseuop id="overlay-${i}-${j}">#</span>`
}
txt += "</div>"
}
document.getElementById('painting').innerHTML += txt
}
function hover(x) {
let id = x.id;
let i = x.id.split('-')[1];
let j = x.id.split('-')[2];
for (let a = -2; a <= 2; a++) {
for (let b = -1; b <= 1; b++) {
const elem = document.getElementById(`overlay-${i-a}-${j-b}`);
elem ? elem.style.opacity = 0 : null;
}
}
x.style.opacity = '0';
}
function hoverOut() {
for (let i = 0; i < document.getElementsByTagName('span').length; i++) {
document.getElementsByTagName('span')[i].style.opacity = 1;
}
}
<body onload="paint()">
<div id="painting">
</div>
</body>
Another approach without using ids would be to use Element.getBoundingClientRect() to get the size and position of the hovered element and then use Document.elementFromPoint() inside a loop to access elements near the hovered one:
const main = document.querySelector('main')
for (let i = 0; i < 800; i++) main.innerHTML += '<span>#</span>'
const spans = document.querySelectorAll('span')
const areaWidth = 50
const areaHeight = 50
const hidden = []
function getElements(currentSpan, color) {
const { top, right, bottom, left, width, height } = currentSpan.getBoundingClientRect()
for (let col = left - areaWidth / 2; col < right + areaWidth / 2; col += width || 14) {
for (let row = top - areaHeight / 2; row < bottom + areaHeight / 2; row += height || 14) {
const el = document.elementFromPoint(col, row)
if (el?.tagName === 'SPAN') {
el.style.color = color
hidden.push(el)
}
}
}
}
spans.forEach(span => {
span.addEventListener('mouseover', () => getElements(span, 'transparent'))
span.addEventListener('mouseout', () => {
hidden.forEach(el => (el.style.color = ''))
hidden.length = 0
})
})
main {
display: flex;
flex-wrap: wrap;
width: 640px;
cursor: default;
}
<main></main>
You could use a CSS solution - overwrite the adjacent characters with a pseudo element on the clicked character.
This snippet uses a monospace font and it's set line height and letter spacing as CSS variables so you can alter them as required.
function clicked(ev) {
ev.target.classList.add('obscure');
}
const container = document.querySelector('.container');
for (let i = 0; i < 200; i++) {
const span = document.createElement('span');
span.innerHTML = '#';
if (i % 10 == 0) {
container.innerHTML += '<br>';
}
container.appendChild(span);
}
container.addEventListener('click', clicked);
.container {
width: 50vw;
height: auto;
font-family: Courier, monospace;
--line-height: 20px;
--letter-spacing: 5px;
line-height: var(--line-height);
letter-spacing: var(--letter-spacing);
}
.container span {
position: relative;
margin: 0;
padding: 0;
}
.obscure::before {
content: '';
width: calc(5ch + (6 * var(--letter-spacing)));
height: calc(3 * var(--line-height));
background-color: white;
position: absolute;
top: 0;
transform: translate(calc(-50% + 0.5ch), calc(-50% + (1ch)));
left: 0;
z-index: 1;
display: inline-block;
}
<body>
<div class="container"></div>
</body>
If I understand you right, you want the span to vanish, but you don't want its space to also vanish. display:none is the wrong solution. you need visibility:hidden.
hiding the hovered element and elements before and after it is easy. the difficulty is in hiding element that are above or below it.
to do that, you would need to do some math.
assuming the answer doesn't need to be exact, you could do it something like this:
calculate the centre positions of all spans and keep them in an array (so you don't need to recalculate every time)
when a span is mouse-entered, check the array and calculate all spans that are within radius r of that span's centre point - or just above/below/left/right - whatever works.
create a new array of spans that should be hidden
check all hidden spans - if any of them are not in that new array, unhide them (visibility:visible)
finally, go through the new array and set visibility:hidden on all spans in that array
Here is a bit diffrent and custumisable aproch:
// Variables
const ROW = 10; // Total number of rows
const COL = 35; // Total number of items in a row (i.e. columns)
const RANGE = 2; // Total number of items to be selected in each direction
const values = []; // To colect ids of items to be selected
// Utility Function
const push = (value) => {
if (value > 0 && value <= ROW * COL && !values.includes(value)) values.push(value);
};
// Add items in the root div
const root = document.querySelector("#root");
for (let i = 0; i < ROW; i++) {
root.innerHTML += `<div id="row-${i + 1}"></div>`;
for (let j = 0; j < COL; j++) {
document.querySelector(`#row-${i + 1}`).innerHTML += `<span id="item-${COL * i + (j + 1)}">#</span>`;
}
}
// Add class to the items as per the RANGE
root.addEventListener("mouseover", (e) => {
values.length = 0;
const id = e.target.id;
if (!id.includes("item-")) return;
const current = +id.replace("item-", "");
push(current);
for (let i = -RANGE; i < RANGE; i++) {
push(current + i);
for (let j = -RANGE; j <= RANGE; j++) {
push(current + COL * i + j);
push(current - COL * i + j);
}
}
for (let i = 0; i < values.length; i++) {
const item = document.querySelector(`#item-${values[i]}`);
item.classList.add("selected");
}
});
// Remove class from the items as per the RANGE
root.addEventListener("mouseout", () => {
for (let i = 0; i < values.length; i++) {
const item = document.querySelector(`#item-${values[i]}`);
item.classList.remove("selected");
}
});
/* Just for styling purposes */
body {
background-color: #111;
color: #fff;
}
#root [id*="item-"] {
padding: 1px;
}
/* Styles for the selected item */
#root [id*="item-"].selected {
/* color: transparent; */ /* 👈 Use this to get your intended effect */
color: #ffa600;
}
<div id="root"></div>
I have a board game and when the user clicks on one of the boxes, it flips over and shows the letter. I wanted to instead have an image displayed when the user clicks instead of a letter. I have an array that holds all of the letters but when replaced with a imageurl, it just shows the url instead of the image. I will paste the html,css and js down below.
js
var memory_array = ["./naruto.gif ", "A", "B", "B", "C", "C", "D", "D"];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function() {
var i = this.length,
j,
temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
};
function newBoard() {
tiles_flipped = 0;
var output = "";
memory_array.memory_tile_shuffle();
for (var i = 0; i < memory_array.length; i++) {
output +=
'<div id="tile_' +
i +
'" onclick="memoryFlipTile(this,\'' +
memory_array[i] +
"')\"></div>";
}
document.getElementById("memory_board").innerHTML = output;
}
function memoryFlipTile(tile, val) {
//if the title is empty and array = 0 then the rest of code will perform
if (tile.innerHTML == "" && memory_values.length < 2) {
//the tile selected will have a white background and the val will be produced
tile.style.background = "#FFF";
tile.innerHTML = val;
//if the array equal = 0
if (memory_values.length == 0) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if the array equal = 1
} else if (memory_values.length == 1) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if memory_values values are the same
if (memory_values[0] == memory_values[1]) {
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if (tiles_flipped == memory_array.length) {
alert("Board cleared... generating new board");
document.getElementById("memory_board").innerHTML = "";
newBoard();
}
} else {
// if the two flip tiles aren't of the same value
function flip2Back() {
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = "orangered";
tile_1.innerHTML = "";
tile_2.style.background = "orangered";
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="app.js"></script>
</head>
<body>
<div id="memory_board"> </div>
<script>
newBoard();
</script>
</body>
</html>
CSS
<style>
div#memory_board {
background: #CCC;
border: #999 1px solid;
width: 800px;
height: 540px;
padding: 24px;
margin: 0px auto;
}
div#memory_board>div {
background: orangered;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
}
</style>
You can create new image and set the src value from the array of image. Also set the width and height.
var img= new Image();
img.src = val;
img.width="50";
img.height="50";
tile.appendChild(img);
See the snippet below:
div#memory_board {
background: #CCC;
border: #999 1px solid;
width: 800px;
height: 540px;
padding: 24px;
margin: 0px auto;
}
div#memory_board>div {
background: orangered;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="memory_board"> </div>
<script>
var memory_array = ["http://www.clker.com/cliparts/b/6/1/0/124223379411527084631_Train_(1967-1979).svg.med.png", "http://www.clker.com/cliparts/b/6/1/0/124223379411527084631_Train_(1967-1979).svg.med.png", "http://www.clker.com/cliparts/Y/y/T/n/Z/Q/number-2-md.png", "http://www.clker.com/cliparts/Y/y/T/n/Z/Q/number-2-md.png", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQo95Lf_9XG0mf3Tb_lfMDUDXiywIdpiiCb5jUSTyOi5ACJXa3C6w", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQo95Lf_9XG0mf3Tb_lfMDUDXiywIdpiiCb5jUSTyOi5ACJXa3C6w", "http://www.clker.com/cliparts/K/w/R/r/V/Z/number-4-hi.png", "http://www.clker.com/cliparts/K/w/R/r/V/Z/number-4-hi.png"];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function() {
var i = this.length,
j,
temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
};
function newBoard() {
tiles_flipped = 0;
var output = "";
memory_array.memory_tile_shuffle();
for (var i = 0; i < memory_array.length; i++) {
output +=
'<div id="tile_' +
i +
'" onclick="memoryFlipTile(this,\'' +
memory_array[i] +
"')\"></div>";
}
document.getElementById("memory_board").innerHTML = output;
}
function memoryFlipTile(tile, val) {
//if the title is empty and array = 0 then the rest of code will perform
if (tile.innerHTML == "" && memory_values.length < 2) {
//the tile selected will have a white background and the val will be produced
tile.style.background = "#FFF";
var img= new Image();
img.src = val;
img.width="50";
img.height="50";
tile.appendChild(img);
//if the array equal = 0
if (memory_values.length == 0) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if the array equal = 1
} else if (memory_values.length == 1) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if memory_values values are the same
if (memory_values[0] == memory_values[1]) {
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if (tiles_flipped == memory_array.length) {
alert("Board cleared... generating new board");
document.getElementById("memory_board").innerHTML = "";
newBoard();
}
} else {
// if the two flip tiles aren't of the same value
function flip2Back() {
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = "orangered";
tile_1.innerHTML = "";
tile_2.style.background = "orangered";
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
newBoard();
</script>
</body>
</html>
You can also test it here
Your code doesn't see the difference between a string representing a url, and a string with some text in it. It's both strings. So, in order to display the image, you'd need to do one of the following:
Create an <img> element, and set that elements src attribute to the url.
Add some css to make the element have a background-image with the url you have, and style that accordingly.
EDIT. Let's just do the first method, because it's a bit easier. The following will create an image with the correct source:
var imageElement = new Image();
imageElement.src = url;
and then we can put it inside an element, for example, putting it inside tile would be
tile.appendChild(imageElement);
EDIT 2. To transform the array of urls into an array of images, one could simply do this:
// your array of urls
var url_array = ["./naruto.gif","fakepath/pikachu.gif"];
// this will create a new array with the same length as url_array
var memory_array = new Array(url_array.length);
// loop through it to put the images in memory_array
for(var i = 0; i < memory_array.length; ++i){
memory_array[i] = new Image();
memory_array[i].src = url_array[i];
}
// now memory_array contains the right images with source set
I am new to JavaScript, and decided to do some practice with displaying n rows of Pascal's triangle. I have everything working, and the rows are displayed in the console, however when I try to push the currentRow to the array of triangle, nothing shows up on the page. Here is how I am attempting to do so:
if (typeof currentRow !== 'undefined') {
console.log('Row ', i - 2);
currentRow = currentRow.join(' ');
console.log(currentRow);
console.log(triangle);
triangle.push('n', currentRow)
triangle = triangle.join('');
}
Any help/advice would be apreciated. I am sure this code is not that efficient (I know it is not optimal to just write out the first 3 rows). Below is a code snippet, and a jsfiddle.
https://jsfiddle.net/keuo8za0/
var row0 = [1];
var row1 = [1, 1];
var row2 = [1, 2, 1];
row0 = row0.join(' ');
row1 = row1.join(' ');
row2 = row2.join(' ');
var triangle = [row0];
triangle.push('\n', row1);
triangle.push('\n', row2);
triangle = triangle.join('');
lastRow = [1, 2, 1];
var submit = document.getElementById('submit');
function buildTriangle(pascalNumber) {
for (let i = 4; i < pascalNumber; i++) {
if (typeof currentRow !== 'undefined') {
console.log('Row ', i - 2);
currentRow = currentRow.join(' ');
console.log(currentRow);
console.log(triangle);
}
var x = i;
var currentRow = [1, 1];
for (let y = 1; y + 1 < x; y++) {
var nextNumber = (lastRow[y - 1] + lastRow[y]);
currentRow.splice(1, 0, nextNumber);
}
lastRow = currentRow;
}
}
function drawTriangle() {
document.getElementById('triangle').innerText = triangle;
}
submit.onclick = function() {
var rownum = document.getElementById('pn').value;
buildTriangle(rownum - 1);
drawTriangle();
return false;
}
body {
background: #4286f4;
font-family: arial;
}
h1 {
font-size: 36px;
text-align: center;
}
h1:hover {
color: #ff35c5;
}
form {
font: sans-serif;
text-align: center;
}
p {
font-size: 36px;
font: sans-serif;
text-align: center;
}
#map {
margin: 0 auto;
width: 80%;
height: 80%;
}
<html>
<head>
<title>Pascal's Triangle</title>
<link rel="stylesheet" href="fancy.css" />
</head>
<body>
<h1>Pascal's Triangle</h1>
<form id='numberOfRows'>
Number of Rows:<br>
<input id='pn' type='number'><br>
<button id='submit'>Submit</button>
</form>
<p id='triangle'></p>
<script src="triangler.js"></script>
</body>
</html>
Interesting... I did it row by row. Found really good help from google..
<style>
body {
background: #4286f4;
font-family: arial;
}
h1 {
font-size: 36px;
text-align: center;
}
h1:hover {
color: #ff35c5;
}
form {
font: sans-serif;
text-align: center;
}
p {
font-size: 36px;
font: sans-serif;
text-align: center;
}
#map {
margin: 0 auto;
width: 80%;
height: 80%;
}
</style>
<h1>Pascal's Triangle</h1>
<form id='numberOfRows'>
Number of Rows:<br>
<input id='pn' type='number'><br>
<button id='submit'>Submit</button>
</form>
<p id='triangle'></p>
<script>
var div = document.getElementById('triangle');
submit.onclick = function() {
div.innerHTML = "";
var rownum = document.getElementById('pn').value;
printPascal(rownum);
return false;
};
function printPascal(n) {
// Iterate through every line and
// print entries in it
for (var line=0; line < n; line++)
{
var lineHTML = "<div class='text-center'>";
// Every line has number of
// integers equal to line
// number
for (var i = 0; i <= line; i++) {
lineHTML += "" + binomialCoeff(line, i) + " ";
}
lineHTML += "</div>\n";
div.innerHTML += lineHTML;
}
}
// for details of this function
function binomialCoeff(n, k)
{
var res = 1;
if (k > n - k)
k = n - k;
for (var i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
</script>
Okay so this is a bit of a weird request. So I've programmed tiles that generate using JavaScript (with the help of people here on stack overflow) now I would like to make it so that on the click of a button my changecolors function is called a set number of times so that the colors of the tiles randomly change before your eyes. I've got a button that every time you click it the colors change, but how can I make it so on that click they continuously change? I've tried using the JavaScript function set Interval(function, time) and couldn't seem to get it to work. Just in case, I will also inform you that I am putting a button in that will also stop the random color changes.. Here's the code. Any help would be great!!
<!doctype html>
<html>
<style>
.cell {
width: 100px;
height: 100px;
display: inline-block;
margin: 1px;
padding:4px;
}
button{
float:left;
padding:4px;
}
</style>
<title></title>
<head><script type="text/javascript">
function generateGrid(){
for (i = 0; i < 5; i++) {
for (b = 0; b < 5; b++) {
div = document.createElement("div");
div.id = "box" + i +""+ b;
div.className = "cell";
document.body.appendChild(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors(){
for(i =0;i < 5; i++){
for (b=0;b<5;b++){
var holder=document.createElement("div");
holder=document.getElementById("box" + i +""+ b);
holder.style.backgroundColor = getRandomColor();
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</head>
<body>
<script>
generateGrid();
changeColors();
</script>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="window.setInterval(changeColors(),2000);">Click me to start cycle</button>
</body>
</html>
Your changeColors() should have been changeColors for window.setInterval.
I cleaned up your code and added the stop/start buttons. By creating an array of elements, it saves the changeColors function having to locate each element every iteration. Lastly I changed your generateGrid function to accept a width and height. A bit overkill but I got carried away :)
HTML
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="startCycle();">Start cycle</button>
<button onclick="stopCycle();">Stop cycle</button>
<br>
<br>
JavaScript
var elements = [];
function generateGrid(width, height) {
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var div = document.createElement("div");
div.id = "box" + y + "" + x;
div.className = "cell";
document.body.appendChild(div);
elements.push(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors() {
for (e in elements) {
elements[e].style.backgroundColor = getRandomColor();
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var interval = null;
function startCycle() {
if (interval) return;
interval = window.setInterval(changeColors, 500);
}
function stopCycle() {
clearInterval(interval);
interval = null;
}
generateGrid(3, 5);
changeColors();
Demo
Simple Just added one function on Click of button try this:
<style>
.cell {
width: 100px;
height: 100px;
display: inline-block;
margin: 1px;
padding:4px;
}
button{
float:left;
padding:4px;
}
</style>
<title></title>
<head><script type="text/javascript">
function generateGrid(){
for (i = 0; i < 5; i++) {
for (b = 0; b < 5; b++) {
div = document.createElement("div");
div.id = "box" + i +""+ b;
div.className = "cell";
document.body.appendChild(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors(){
for(i =0;i < 5; i++){
for (b=0;b<5;b++){
// var holder=document.createElement("div");
var holder=document.getElementById("box" + i +""+ b);
holder.style.backgroundColor = getRandomColor();
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</head>
<body>
<script>
generateGrid();
changeColors();
function animate1()
{
setInterval(function(){
changeColors();
},5000);
}
</script>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="animate1();">Click me to start cycle</button>
</body>
Note: setTimeout function gets called only once after your set duration where setTimeout gets called indefinite unless you use clearInterval() to Stop it.
Your setTimeoutFunction was not sintatically correct
var stop = false;
function generateGrid(){
for (i = 0; i < 5; i++) {
for (b = 0; b < 5; b++) {
div = document.createElement("div");
div.id = "box" + i +""+ b;
div.className = "cell";
document.body.appendChild(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors(){
for(i =0;i < 5; i++){
for (b=0;b<5;b++){
var holder=document.createElement("div");
holder=document.getElementById("box" + i +""+ b);
holder.style.backgroundColor = getRandomColor();
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
document.addEventListener("DOMContentLoaded", function(event) {
generateGrid();
changeColors();
});
.cell {
width: 100px;
height: 100px;
display: inline-block;
margin: 1px;
padding:4px;
}
button{
float:left;
padding:4px;
}
<!doctype html>
<html>
<title></title>
<body>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="window.setInterval(function(){changeColors();},2000);">Click me to start cycle</button>
</body>
</html>
Edited to work without jQuery
I am trying to make a grid in an HTML using plain Javascript. I have a URL in which number is given and basis on that I am generating a grid.
My url is like this abc.html?num=5 and basis on this num=5 I need to generate a grid of 5x5 size.
Currently I am using jQuery but I want to see how we can do the same thing with plain Javascript. Here is my jsfiddle example.
Below is my full content of abc.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var defaultNum = 4;
var url = window.location.search;
var num = parseInt(url.split('num=')[1]) || defaultNum;
var container = $('#container');
var width = container.outerWidth();
createGrid(num);
function createGrid(n) {
if (!$.isNumeric(n) || n <= 0) return;
for (var i = 0; i < n * n; i++) {
var dimension = width / n;
var cell = $('<div/>').addClass('gridCell').css({
'width': dimension + 'px',
'height': dimension + 'px'
});
container.append(cell);
}
}
});
</script>
<style>
#container {
width: 300px;
height: 300px;
}
#container > .gridCell {
float: left;
padding: 0;
margin: 0;
border: 0;
outline: 1px solid;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
How can I do the same thing with plain Javascript instead of using any libraries like jquery which I am using currently?
This can't be demonstrated in a jsfiddle because it requires access to the url. But here is the code, put it in an HTML and test it out:
<html>
<style>
#container {
width: 300px;
height: 300px;
}
#container > .gridCell {
float: left;
padding: 0;
margin: 0;
border: 0;
outline: 1px solid;
}
</style>
<body>
<div id="container">
</div>
<script>
// QueryString is the function that gets the num parameter.
// Source to this function: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
var defaultNum = 3;
var num = parseInt(QueryString.num) || defaultNum;
var container = document.getElementById('container');
var width = container.offsetWidth;
createGrid(num);
function createGrid(n) {
// If n is not a number or smaller than 0
if(isNaN(n) || n <= 0)
return;
for(var i = 0; i < n*n; i++) {
var dimension = width/n;
var cell = document.createElement('div');
cell.className = cell.className + ' gridCell';
cell.style.width = dimension + 'px';
cell.style.height = dimension + 'px';
container.appendChild(cell);
}
}
</script>
</body>
</html>