I am currently working on a draggable, droppable image in a grid. Here each box in the grid is a div and each icon is an element. I want each icon element in the center of each box in the grid. But failed to do so. Please Help me out. I know I am missing something very common , but cant get the idea right now.Here is my code.
function makeDraggable() {
$(".far").draggable({
helper: "clone"
})
$(".far").droppable({
drop: function (ev, ui) {
$(ui.draggable).clone().replaceAll(this);
$(this).replaceAll(ui.draggable);
makeDraggable();
}
})
}
function randomColor(colors = ["green", "red", "blue", "yellow", "white", "orange"]){
return colors[Math.floor(Math.random() * colors.length)];
};
function randomIcons(){
var icon = ["far fa-angry","far fa-address-card","far fa-address-book","far fa-arrow-alt-circle-down","far fa-arrow-alt-circle-up"];
return icon[Math.floor(Math.random() * icon.length)];
//return icon
};
function generateGrid() {
x = parseInt(document.getElementById('xaxis').value)
y = parseInt(document.getElementById('yaxis').value)
colors = ["green", "red", "blue", "yellow", "white", "orange"]
container = document.createElement("div");
container.id = "main";
container.className = "container";
for (let i = 0; i < x; i++) {
row = document.createElement("div");
row.className = "row";
row.id = "row" + i;
for (let j = 0; j < y; j++) {
box = document.createElement("div");
box.className = "box";
box.style.backgroundColor = randomColor(colors);
row.appendChild(box);
icons = document.createElement("i")
icons.className = randomIcons()
box.appendChild(icons);
}
container.appendChild(row);
}
let app = document.getElementById("app");
app.appendChild(container);
makeDraggable();
};
function resetUI(){
document.getElementById("app").innerHTML = "";
}
body {
font-family: cursive;
}
.container {
display: flex;
flex-direction: row;
}
.box {
border: 1px solid black;
height: 100px;
width: 100px;
}
html{
background-image: url('https://images.pexels.com/photos/1435752/pexels-photo-1435752.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260');
}
#full1{
margin: 150px;
margin-top: 10px;
margin-left: 30%;
margin-right: 30%;
/* background-color: whitesmoke; */
}
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Notice how this gets configured before we load Font Awesome
window.FontAwesomeConfig = { autoReplaceSvg: false }
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.js" integrity="sha512-AsoAG+OFcSvtqlspW166UTUYg7F4GEu0yNhzTIRfOGysIQA8Dqk1WZwyoN4eX6mX4DaSk703Q1iM0M47rw25Kw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js" integrity="sha384-cn7l7gDp0eyniUwwAZgrzD06kc/tftFf19TOAs2zVinnD/C7E91j9yyk5//jjpt/" crossorigin="anonymous"></script> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div id="full1">
<form style="text-align: center;">Draggable Grid<br><br><br>
<label for="fname">Boxes on X axis:</label>
<input type="text" placeholder="Max value < 8" id="xaxis"><br><br>
<label for="lname">Boxes on Y axis:</label>
<input type="text" placeholder="Max value < 5" id="yaxis"><br><br>
<input type="button" class="btn btn-primary" onclick="generateGrid()" value="Submit">
<input type="button" onclick="resetUI()" value="Clear">
</form>
<div id="app" style="position:fixed;
top: 36%;
left: 30%; "></div>
</div>
</body>
</html>
You can use flex and align and justify element center.
.box{
display: flex;
align-items: center;
justify-content: center;
}
If you set flex display properties for each created box element you can align the icon to the center with align-items and justify-content
function makeDraggable() {
$(".far").draggable({
helper: "clone"
})
$(".far").droppable({
drop: function (ev, ui) {
$(ui.draggable).clone().replaceAll(this);
$(this).replaceAll(ui.draggable);
makeDraggable();
}
})
}
function randomColor(colors = ["green", "red", "blue", "yellow", "white", "orange"]){
return colors[Math.floor(Math.random() * colors.length)];
};
function randomIcons(){
var icon = ["far fa-angry","far fa-address-card","far fa-address-book","far fa-arrow-alt-circle-down","far fa-arrow-alt-circle-up"];
return icon[Math.floor(Math.random() * icon.length)];
//return icon
};
function generateGrid() {
x = parseInt(document.getElementById('xaxis').value)
y = parseInt(document.getElementById('yaxis').value)
colors = ["green", "red", "blue", "yellow", "white", "orange"]
container = document.createElement("div");
container.id = "main";
container.className = "container";
for (let i = 0; i < x; i++) {
row = document.createElement("div");
row.className = "row";
row.id = "row" + i;
for (let j = 0; j < y; j++) {
box = document.createElement("div");
box.className = "box";
box.style.backgroundColor = randomColor(colors);
row.appendChild(box);
icons = document.createElement("i")
icons.className = randomIcons()
box.appendChild(icons);
}
container.appendChild(row);
}
let app = document.getElementById("app");
app.appendChild(container);
makeDraggable();
};
function resetUI(){
document.getElementById("app").innerHTML = "";
}
body {
font-family: cursive;
}
.container {
display: flex;
flex-direction: row;
}
.box {
border: 1px solid black;
height: 100px;
width: 100px;
/* set flex properties here to align icon to centre of div */
display:flex;
align-items:center;
justify-content:center;
}
html{
background-image: url('//images.pexels.com/photos/1435752/pexels-photo-1435752.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260');
}
#full1{
margin: 150px;
margin-top: 10px;
margin-left: 30%;
margin-right: 30%;
/* background-color: whitesmoke; */
}
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js'></script>
<script>
window.FontAwesomeConfig = { autoReplaceSvg: false }
</script>
<script src='//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.js' integrity='sha512-AsoAG+OFcSvtqlspW166UTUYg7F4GEu0yNhzTIRfOGysIQA8Dqk1WZwyoN4eX6mX4DaSk703Q1iM0M47rw25Kw==' crossorigin='anonymous' referrerpolicy='no-referrer'></script>
<link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css' integrity='sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==' crossorigin='anonymous' referrerpolicy='no-referrer' />
<div id='full1'>
<form style='text-align: center;'>Draggable Grid<br><br><br>
<label for='fname'>Boxes on X axis:</label>
<input type='text' placeholder='Max value < 8' id='xaxis'><br><br>
<label for='lname'>Boxes on Y axis:</label>
<input type='text' placeholder='Max value < 5' id='yaxis'><br><br>
<input type='button' class='btn btn-primary' onclick='generateGrid()' value='Submit'>
<input type='button' onclick='resetUI()' value='Clear'>
</form>
<div id='app' style='position:fixed; top: 36%; left: 30%; '></div>
</div>
Related
I had a hard time coding, so I asked a question here.
If you press the button on the upper left, you can make the color boxes invisible. At the same time, I wrote down the code the the button can make the color boxes could be placed in a random location.
I would like to make sure that the color boxes do not go out of the screen. Even if the width and height were set to 100% on the body, the color box was placed off the screen.
And I want to correct the color boxes so that they can be moved by draggable function, but they don't work together. I would also like to ask for help with this.
and I am not a coding expert man so, I need a comment with coding example.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
body {margin:0; padding:0;}
button {position: absolute; width: 30px; height: 30px; background: #edd6bc;}
.random {position: absolute; width: 30px; height: 30px;}
</style>
<script>
</script>
</head>
<body >
<button onclick="showhide()" value="Zeige Features" id="button"></button>
<div style="display: none; background: #6d97b4;" class="random" ></div>
<div style="display: none; background: #c9656f;" class="random" ></div>
<div style="display: none; background: #f1eb40;" class="random" ></div>
<div style="display: none; background: #00825c;" class="random" ></div>
<div style="display: none; background: #009ce0;" class="random" ></div>
<div style="display: none; background: #cee4a6;" class="random" ></div>
<script type="text/javascript">
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const boxes = document.querySelectorAll(".random");
btn.addEventListener("click", () => {
Array.from(boxes).forEach(box => {
box.style.top = Math.floor((Math.random() * height) + 1) + "px";
box.style.right = Math.floor((Math.random() * width) + 1) + "px";
})
});
function showhide() {
var x = document.querySelectorAll(".random");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
</script>
</body>
</html>
If you want an explanation tell me.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
body {margin:0; padding:0;}
button {position: absolute; width: 30px; height: 30px; background: #edd6bc;}
.random {position: absolute; width: 30px; height: 30px;}
</style>
<script>
</script>
</head>
<body >
<button onclick="showhide()" value="Zeige Features" id="button"></button>
<div style="display: none; background: #6d97b4;" class="random"></div>
<div style="display: none; background: #c9656f;" class="random"></div>
<div style="display: none; background: #f1eb40;" class="random"></div>
<div style="display: none; background: #00825c;" class="random"></div>
<div style="display: none; background: #009ce0;" class="random"></div>
<div style="display: none; background: #cee4a6;" class="random"></div>
<script type="text/javascript">
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight - 30;
const width = document.documentElement.clientWidth - 30;
const boxes = document.querySelectorAll(".random");
btn.addEventListener("click", () => {
Array.from(boxes).forEach(box => {
box.style.top = Math.floor(Math.random() * height) + "px";
box.style.left = Math.floor(Math.random() * width) + "px";
})
});
function showhide() {
var x = document.querySelectorAll(".random");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
function mouseDown(downEvent) {
var box = downEvent.srcElement;
var offX = box.getBoundingClientRect().left - downEvent.x;
var offY = box.getBoundingClientRect().top - downEvent.y;
document.onmousemove = e => {
box.style.top = Math.min(Math.max(e.y + offY, 0), height) + "px";
box.style.left = Math.min(Math.max(e.x + offX, 0), width) + "px";
}
document.onmouseup = e => {
document.onmousemove = document.onmouseup = null;
}
return false;
}
Array.from(boxes).forEach(box => {
box.onmousedown = mouseDown;
})
</script>
</body>
</html>
While generating the top * right subtract the height and width of the div
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const boxes = document.querySelectorAll(".random");
btn.addEventListener("click", () => {
Array.from(boxes).forEach(box => {
const top = Math.floor(Math.random() * (height - 30) + 1) + "px";
const right = Math.floor(Math.random() * (width - 30) + 1) + "px";
box.style.top = top;
box.style.right = right;
})
});
function showhide() {
var x = document.querySelectorAll(".random");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
margin: 0;
padding: 0;
}
button {
position: relative;
width: 30px;
height: 30px;
background: #edd6bc;
}
.random {
position: absolute;
width: 30px;
height: 30px;
}
<button onclick="showhide()" value="Zeige Features" id="button"></button>
<div style="display: none; background: #6d97b4;" class="random"></div>
<div style="display: none; background: #c9656f;" class="random"></div>
<div style="display: none; background: #f1eb40;" class="random"></div>
<div style="display: none; background: #00825c;" class="random"></div>
<div style="display: none; background: #009ce0;" class="random"></div>
<div style="display: none; background: #cee4a6;" class="random"></div>
I'm making an Etch a sketch game in JS.
I have a two questions:
1) How to set a function to all elements in grid?
cellArray.forEach(elem => {
elem.addEventListener('mouseover', () => {
elem.style.backgroundColor = 'red';
});
});
When i change color like that, it's changing for all cells, but when i try with function it's change only the last one, when i mouseover of any of it.
2) How can i do my grid change size every time when the input.value changed by user, without reloading the page? I think about AJAX, but i'm very new one, so i don't know much.
let sketch = document.querySelector('#sketch-grid'),
cellArray = [],
input = document.querySelector('.input-skh'),
cellNumber;
cellNumber = input.value;
let colors = {
blue: function () {
cell.style.backgroundColor = 'blue';
},
white: function () {
cell.style.backgroundColor = 'white';
},
random: function () {
let r = Math.floor(Math.random() * (256)),
g = Math.floor(Math.random() * (256)),
b = Math.floor(Math.random() * (256)),
randomColor = '#' + r.toString(16) + g.toString(16) + b.toString(16);
cell.style.backgroundColor = randomColor;
}
};
function buildGrid(){
sketch.style.gridTemplateRows = `repeat(${cellNumber}, auto)`;
sketch.style.gridTemplateColumns = `repeat(${cellNumber}, auto)`;
for (let i = 0; i < cellNumber * cellNumber; i++){
cell = document.createElement('div');
cell.classList.add('cell');
sketch.appendChild(cell);
cellArray.push(cell);
}
}
input.addEventListener('oninput', buildGrid());
/*let cellNumber = +prompt('The size of sketch is: ');*/
function changeColor(){
colors.random();
}
cellArray.forEach(elem => elem.addEventListener('mouseover', changeColor()));
* {
box-sizing: border-box;
}
.sketch-input {
margin: auto;
text-align: center;
background-color: lightseagreen;
}
.sketch-input .input-skh {
width: 300px;
height: 70px;
background-color: mediumpurple;
font-size: 40px;
color: white;
}
.sketch-input label {
color: white;
font-size: 35px;
}
.wrapper-sketch {
width: 100%;
height: 800px;
background-color: black;
padding: 20px;
}
.wrapper-sketch #sketch-grid {
display: grid;
margin: 10px auto;
width: 500px;
height: 500px;
}
.wrapper-sketch #sketch-grid div {
border: 2px solid crimson;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Etch a sketch</title>
<link rel="stylesheet" href="../templates/main.css">
</head>
<body>
<div class="sketch-input">
<label>Choose a size of your sketch:</label>
<input class="input-skh" type="range" min="3" max="50">
</div>
<div class="wrapper-sketch">
<div id="sketch-grid"></div>
</div>
<div class="buttons">
<button class="button__choose-color">Change Color</button>
<button class="button__reset">RESET</button>
</div>
<script src="../js/app.js"></script>
</body>
</html>
Checkout the fixes in snippet below:
Minor changes:
cellArray.forEach(elem => elem.addEventListener('mouseover', () => changeColor(elem)));
Register the event handler function instead of calling changeColor() function immediately. Also pass in the current elem to the function.
random: function (elem) {
let r = Math.floor(Math.random() * (256)),
g = Math.floor(Math.random() * (256)),
b = Math.floor(Math.random() * (256)),
randomColor = '#' + r.toString(16) + g.toString(16) + b.toString(16);
elem.style.backgroundColor = randomColor;
}
Use the elem as the argument/parameter instead of using global cell value.
Expand and see snippet below:
let sketch = document.querySelector('#sketch-grid'),
cellArray = [],
input = document.querySelector('.input-skh'),
cellNumber;
cellNumber = input.value;
let colors = {
blue: function () {
cell.style.backgroundColor = 'blue';
},
white: function () {
cell.style.backgroundColor = 'white';
},
random: function (elem) {
let r = Math.floor(Math.random() * (256)),
g = Math.floor(Math.random() * (256)),
b = Math.floor(Math.random() * (256)),
randomColor = '#' + r.toString(16) + g.toString(16) + b.toString(16);
elem.style.backgroundColor = randomColor;
}
};
function buildGrid(){
sketch.style.gridTemplateRows = `repeat(${cellNumber}, auto)`;
sketch.style.gridTemplateColumns = `repeat(${cellNumber}, auto)`;
for (let i = 0; i < cellNumber * cellNumber; i++){
cell = document.createElement('div');
cell.classList.add('cell');
sketch.appendChild(cell);
cellArray.push(cell);
}
}
input.addEventListener('oninput', buildGrid());
/*let cellNumber = +prompt('The size of sketch is: ');*/
function changeColor(elem){
colors.random(elem);
}
cellArray.forEach(elem => elem.addEventListener('mouseover', () => changeColor(elem)));
* {
box-sizing: border-box;
}
.sketch-input {
margin: auto;
text-align: center;
background-color: lightseagreen;
}
.sketch-input .input-skh {
width: 300px;
height: 70px;
background-color: mediumpurple;
font-size: 40px;
color: white;
}
.sketch-input label {
color: white;
font-size: 35px;
}
.wrapper-sketch {
width: 100%;
height: 800px;
background-color: black;
padding: 20px;
}
.wrapper-sketch #sketch-grid {
display: grid;
margin: 10px auto;
width: 500px;
height: 500px;
}
.wrapper-sketch #sketch-grid div {
border: 2px solid crimson;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Etch a sketch</title>
<link rel="stylesheet" href="../templates/main.css">
</head>
<body>
<div class="sketch-input">
<label>Choose a size of your sketch:</label>
<input class="input-skh" type="range" min="3" max="50">
</div>
<div class="wrapper-sketch">
<div id="sketch-grid"></div>
</div>
<div class="buttons">
<button class="button__choose-color">Change Color</button>
<button class="button__reset">RESET</button>
</div>
<script src="../js/app.js"></script>
</body>
</html>
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Online Drawing Program</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="canvas"></div>
<script src="script.js"></script>
</body>
</html>
Javascript:
function drawingProgram(width, height) {
this.width = width;
this.height = height;
this.mousedown = false;
this.makeCanvas = function () {
for (var row = 0; row <= this.height; row++) {
$("#canvas").append("<div class='row' id='row" + row + "'></div>");
for (var col = 0; col <= height; col++) {
$("#row" + row).append("<div class='pixel'></div>");
}
}
}
this.draw = function (el) {
console.log("drawing");
$(el).css({ "background-color": "black" });
}
}
var drawing = new drawingProgram(50, 50);
drawing.makeCanvas();
$("body").on("mousedown", function () { drawing.mousedown = true });
$("body").on("mouseup", function () { drawing.mousedown = false });
$(".pixel").on("mouseover", function () {
if (drawing.mousedown) {
drawing.draw(this);
}
});
CSS:
.row {
display:block;
margin-top:-12px;
}
.pixel {
user-select: none;
flex-wrap:wrap;
display:inline-block;
width:5px;
height:5px;
border:1px solid black;
}
The program in action is here: https://online-drawing-program.powercoder.repl.co/
Problem: the program only makes the pixels at the bottom of my canvas div black. It's only detecting when I'm pressing the bottom pixels. But, I want to detect all my pixel divs.
The pixels are too small, and other CSS problems.
I added a color-picker just for fun.
function drawingProgram(width, height) {
this.width = width;
this.height = height;
this.mousedown = false;
this.color = "black"
this.makeCanvas = function() {
for (var row = 0; row <= this.height; row++) {
$("#canvas").append("<div class='row' id='row" + row + "'></div>");
for (var col = 0; col <= this.width; col++) {
$("#row" + row).append("<div class='pixel'></div>");
}
}
}
this.draw = function(el) {
console.log("drawing");
$(el).css({
"background-color": this.color
});
}
return this
}
var drawing = new drawingProgram(20, 20);
drawing.makeCanvas();
$("body").on("mousedown", function(e) {
drawing.mousedown = true
});
$("body").on("mouseup", function(e) {
drawing.mousedown = false
});
$(".pixel").on("mouseover", function() {
if (drawing.mousedown) {
drawing.draw(this);
}
});
$("#colorpicker div").on("click", function() {
drawing.color = $(this).data("color")
})
#colorpicker {
width: 100px;
height: 20px;
display: flex;
border: 1px solid black;
}
#colorpicker div {
display: block;
width: 20px;
height: 20px;
}
.row {
display: block;
margin: 0;
line-height: 1;
height: 12px;
}
.pixel {
user-select: none;
flex-wrap: wrap;
display: inline-block;
width: 10px;
height: 10px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="colorpicker">
<div data-color="red" style="background-color: red;"></div>
<div data-color="yellow" style="background-color: yellow;"></div>
<div data-color="green" style="background-color: green;"></div>
<div data-color="black" style="background-color: black;"></div>
<div data-color="white" style="background-color: white;"></div>
</div>
<div id="canvas"></div>
SUGGESTION
If you want a drawing program then you should check out the canvas API - that's exactly for these kinds of things.
More on canvas:
basic: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
tutorial: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial
I am trying to create a grid which takes a user input and uses that as its number of rows and columns. In other words, if the user inputs X, I want the grid to have X rows and X columns, and be square, meaning the boxes are as high as they are wide.
I have gotten it to work with JavaScript and CSS grid, but only if I already know the number of rows/columns, in that case 10. Please see below.
How can I create a grid that does the same but with any number of rows and columns?
#container {
display: grid;
grid-template-columns: repeat(10, 1fr);
width: 500px;
height: 500px;
}
div {
width: 100%;
height: 100%;
outline: 1px solid;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-sketch</title>
</head>
<body>
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container"></div>
</body>
<script>
let btn = document.getElementById("start")
btn.addEventListener("click", createGrid)
function createGrid() {
let numberOfRows = prompt("How many rows do you want?");
let i = 0;
let x = numberOfRows ** 2;
for (i; i < x; i++) {
var div = document.createElement("div");
document.getElementById("container").appendChild(div);
div.addEventListener("mouseenter", function() {
this.style.backgroundColor = "red";
});
}
}
</script>
</html>
You can use CSS variable for that. and change the variable value using javascript.
let btn = document.getElementById("start")
btn.addEventListener("click", createGrid)
function createGrid() {
var Container = document.getElementById("container");
Container.innerHTML = '';
let numberOfRows = prompt("How many rows do you want?");
let i = 0;
let x = numberOfRows * numberOfRows;
document.documentElement.style.setProperty("--columns-row", numberOfRows);
for (i = 0; i < x ; i++) {
var div = document.createElement("div");
document.getElementById("container").appendChild(div);
div.addEventListener("mouseenter", function () {
this.style.backgroundColor = "red";
});
}
}
:root {
--columns-row: 2;
}
#container {
display: grid;
grid-template-columns: repeat(var(--columns-row), 1fr);
grid-template-rows: repeat(var(--columns-row), 1fr);
width: 500px;
height: 500px;
}
div {
border: 1px solid #000;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-sketch</title>
</head>
<body>
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container">
</div>
</body>
</html>
Change your css as per your need. jsfiddle.net/926pd5oh/9
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container"></div>
<style>
#container>div {
width: 100%;
height: 10px;
margin: 2px;
}
#container>div>div {
float: left;
height: 10px;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
width: 25px;
}
</style>
<script>
let btn = document.getElementById("start")
btn.addEventListener("click", createGrid);
function createGrid() {
let numberOfRows = prompt("How many rows do you want?");
document.getElementById("container").innerHTML = "";
console.log(numberOfRows);
for (let i = 0; i < numberOfRows; i++) {
var divRow = document.createElement("div");
document.getElementById("container").appendChild(divRow);
for (let y = 0; y < numberOfRows; y++) {
let divCol = document.createElement("div");
divCol.addEventListener("mouseenter", function () {
this.style.backgroundColor = "red";
});
divRow.appendChild(divCol);
}
}
}
</script>
I've ended up using a different tool: container.style.gridTemplateColumns and container.style.gridTemplateRows to affect the number of rows and columns of the container. This allows me not to use the :root function above. See JavaScript Syntax at https://www.w3schools.com/cssref/pr_grid-template-columns.asp
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-sketch</title>
</head>
<body>
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container"></div>
</body>
<script>
//randomColor function is taken from http://www.devcurry.com/2010/08/generate-random-colors-using-javascript.html //
function randomRgb(value) {
col = "rgb("
+ randomColor(255) * value + ","
+ randomColor(255) * value + ","
+ randomColor(255) * value + ")";
}
function randomColor(num) {
return Math.floor(Math.random() * num);
}
function resetColorOfBoxes() {
boxes = document.querySelectorAll('div');
boxes.forEach(box => box.style.backgroundColor = "white");
}
function promptEntry() {
let userInput = prompt("How many rows would you like?", "Enter a number");
if (isNaN(userInput)) {
alert("That's not a valid entry. Try again");
promptEntry();
}
else {
createGrid(userInput);
}
}
function createGrid(numberOfRows) {
resetColorOfBoxes()
let gridTemplateColumns = 'repeat('+numberOfRows+', 1fr)'
var container = document.getElementById("container");
container.style.gridTemplateColumns = gridTemplateColumns;
container.style.gridTemplateRows = gridTemplateColumns;
let brightness = [];
let i = 0;
let numberOfBoxes = numberOfRows**2;
/*Create boxes*/
for (i; i < numberOfBoxes ; i++) {
brightness[i+1] = 1;
console.log(brightness);
var div = document.createElement("div");
div.classList.add(i+1);
document.getElementById("container").appendChild(div);
div.addEventListener("mouseenter", function () {
var className = this.className;
brightness[className] = brightness[className] - 0.1;
console.log(brightness[className]);
randomRgb(brightness[className]);
this.style.backgroundColor = col;
});
}
}
let btn = document.getElementById("start")
btn.addEventListener("click", promptEntry)
</script>
</html>
I am working on the Odin project's javascript/jquery project to make an etcha sketch(of sorts). Initially the webpage loads fine, but when I attempt to change the size of the "gridval" with a prompt, only the box sizes change but not how many boxes fill the given space.
Thanks for your help in advance.
HTML
<!DCOTYPE html>
<html>
<head>
<title>Java Project</title>
<link rel="icon" href="https://www.codementor.io/assets/page_img/learn-javascript.png">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<button class="clear_button">Clear screen</button>
<div id="container"></div>
<script>creategrid();</script>
<script>hovereffect();</script>
</body>
</html>
CSS
#container{
width:400px;
height:400px;
background-color: #fc6;
}
.box{
width:52px;
height:52px;
display:inline-block;
margin: 1px;
background-color: #f86;
}
.clear_button{
background-color: #fc6;
color: #ffe;
border:none;
border-radius: 2px;
padding: 10px;
margin: 10px;
}
.clear_button:hover{
background-color: #426;
}
JavaScript
gridval = 16;
function creategrid(){
$(document).ready(function(){
//make grid code
for(var x = 0; x < gridval; x++){
for(var y = 0; y < gridval; y++){
var box = $("<div class='box'></div>");
box.appendTo('#container');
}
}
var width_height = 400/gridval - 2;
var box_class = document.querySelectorAll(".box");
for(var i = 0; i < box_class.length; i++){
box_class[i].style.width = width_height;
box_class[i].style.height = width_height;
}
//clear button code
$(".clear_button").click(function(){
$(".box").css("background-color", "#f86");
var val = gridval;
gridval = prompt("Please enter a value between 2 and 100 for the grid size!", val);
if(gridval != null) {
var width_height = 400/gridval - 2;
var box_class = document.querySelectorAll(".box");
for(var i = 0; i < box_class.length; i++){
box_class[i].style.width = width_height;
box_class[i].style.height = width_height;
}
}
});
});
}
//hover effect code
function hovereffect(){
$(document).ready(function(){
$(".box").hover(function(){
$(this).css("background-color", "#0ba");
}, function(){
$(this).css("background-color", "#9dd");
});
});
}
Your code needs a total reform, see the comments:
//The ready event will only be triggred once; on your page load.
$(function() {
//Default value
var gridval = 16;
/**
* Create the grid
*/
function createGrid(gridval) {
//make grid code
for (var x = 0; x < gridval; x++) {
for (var y = 0; y < gridval; y++) {
var box = $("<div class='box'></div>");
box.appendTo('#container');
}
}
var width_height = (400 / gridval) - 2;
var box_class = document.querySelectorAll(".box");
for (var i = 0; i < box_class.length; i++) {
box_class[i].style.width = width_height+'px'; //You needed +'px' here
box_class[i].style.height = width_height+'px'; //You needed +'px' here
}
}
//Execute the function on load
createGrid(gridval);
//Event delegation on since your elements will be created dynamically
$(document).on({mouseenter: function() {
$(this).css("backgroundColor", "#0ba");//backgroundColor instead of background-color
}, mouseleave: function() {
$(this).css("backgroundColor", "#9dd");
}}, ".box");
//clear button code
$(".clear_button").click(function() {
//$(".box").css("backgroundColor", "#f86"); // you don't need this all the elements will be removed!
var val = gridval;
gridval = prompt("Please enter a value between 2 and 100 for the grid size!", val);
if (gridval != null) {
//Empty the container
$("#container").empty();
createGrid(gridval);
}
});
});
#container {
width: 400px;
height: 400px;
background-color: #fc6;
}
.box {
width: 52px;
height: 52px;
/* Remove inline block */
display: block;
/* Add float*/
float:left;
margin: 1px;
background-color: #f86;
}
.clear_button {
background-color: #fc6;
color: #ffe;
border: none;
border-radius: 2px;
padding: 10px;
margin: 10px;
}
.clear_button:hover {
background-color: #426;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="clear_button">
Clear screen</button>
<div id="container"></div>