Why is my Jquery mousedown event not working - javascript

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

Related

how can I let 3 div elements being resizable

what I want to see the result is 2 set of split view screen (or more), one is vertical, one is horizontal, but in the same javascript file. If it's possible to do in a single JavaScript file will be good
I tried to use this one to make it but it seems like not how to make that.
Here's the code I'm trying to make two div elements and its vertical
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my app</title>
<style>
.container {
width: 202px;
height: 406px;
border: 1px solid black;
display: flex;
flex-direction: column;
}
.top {
width: 200px;
height: 200px;
border: 1px solid red;
min-height: 100px;
}
.resizer {
width: 202px;
height: 2px;
background-color: green;
}
.resizer:hover {
cursor: ns-resize;
}
.bottom {
width: 200px;
height: 200px;
border: 1px solid blue;
flex: 1 1 0%;
min-height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="top" id="top">
something here
</div>
<div class="resizer" id="resizer"></div>
<div class="bottom" id="bottom">
something too
</div>
</div>
<script>
const resizer = document.getElementById('resizer');
const topSection = document.getElementById('top');
const bottomSection = document.getElementById('bottom');
let x = 0;
let y = 0;
let topSectionHeight = 0;
const mouseDownHandler = function (e) {
x = e.clientX;
y = e.clientY;
topSectionHeight = topSection.getBoundingClientRect().height;
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
}
resizer.addEventListener('mousedown', mouseDownHandler);
const mouseMoveHandler = function (e) {
const dx = e.clientX - x;
const dy = e.clientY - y;
const newtopSectionHeight = ((topSectionHeight + dy) * 100) / resizer.parentNode.getBoundingClientRect().height;
topSection.style.height = `${newtopSectionHeight}%`;
resizer.style.cursor = 'ns-resize';
document.body.style.cursor = 'ns-resize';
topSection.style.userSelect = 'none';
topSection.style.pointerEvents = 'none';
bottomSection.style.userSelect = 'none';
bottomSection.style.pointerEvents = 'none';
}
const mouseUpHandler = function () {
resizer.style.removeProperty('cursor');
document.body.style.removeProperty('cursor');
actionBasic.style.removeProperty('user-select');
actionBasic.style.removeProperty('pointer-events');
bottomSection.style.removeProperty('user-select');
bottomSection.style.removeProperty('pointer-events');
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
}
</script>
</body>
</html>
thank you for reading so far, please help me if you're able to! If any information is needed, please tell me below and I'll provide it as soon as possible.

Make each <i> element in the center of the div element

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>

ask for making divs draggable and not placed off the screen

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>

Track position of other element

I have an inner circle which tracks the position of my pointer, Now I want the circle color to change when it hovers on the h2 tag.
can anyone help??
I have tried searching few places but all were on "mouseover".
note: only when the inner-circle hovers on h2 not the mouse pointer, the inner circle's color should change.
<!doctype>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Roll Over Eyes</title>
<style>
body
{
display: flex;
align-items: center;
justify-content: center;
height: 900px;
border: 1px solid black;
}
.main-circle
{
display: flex;
align-items: center;
justify-content: center;
position: relative;
height: 350px;
width: 350px;
border: 1px solid black;
border-radius: 10%;
}
#inner-circle
{
position: absolute;
height: 50px;
width: 50px;
border: 1px solid black;
border-radius: 50%;
background: #af4b23;
}
.message
{
display:none;
width: 75%;
}
</style>
</head>
<body>
<div class="main-circle">
<div id="inner-circle">
</div>
<h2 class="message">Your Outside the box</h2>
<h2 class="message">Your inside the box, now move the mouse to move the circle.</h2>
</div>
<script>
(function()
{
var ele= document.getElementById("inner-circle");
var hea= document.getElementsByClassName("message");
var body=document.body;
var height=body.clientHeight;
var width=body.clientWidth;
var move = function(event)
{
var x= event.clientX;
var y= event.clientY;
ele.style.left = ( x/width )*300;
ele.style.top = ( y/height )*300;
}
var display = function()
{
console.log("done");
hea[0].style.display="inline-block";
hea[1].style.display="none";
}
var hide = function()
{
console.log("done hiden");
hea[0].style.display="none";
hea[1].style.display="inline-block";
}
var effect = function()
{
ele.style.backgroundColor= "rgba(0,0,0,0.5)";
}
var deflt = function()
{
ele.style.backgroundColor= "#af4b23";
}
body.addEventListener("mousemove",function(){ move(event) },false);
body.addEventListener("mouseout",display,false);
body.addEventListener("mouseover",hide,false);
hea[1].addEventListener("mouseover",effect,false);
hea[1].addEventListener("mouseout",deflt,false);
})();
</script>
</body>
</html>
You can try this:
(function()
{
var ele= document.getElementById("inner-circle");
var hea= document.getElementsByClassName("message");
var body=document.body;
var height=body.clientHeight;
var width=body.clientWidth;
var move = function(event)
{
var x= event.clientX;
var y= event.clientY;
ele.style.left = ( x/width )*300;
ele.style.top = ( y/height )*300;
var e_pos = ele.getBoundingClientRect();
var h_pos = hea[1].getBoundingClientRect();
if(e_pos.bottom>=h_pos.top && e_pos.top<=h_pos.bottom && e_pos.right>=h_pos.left && e_pos.left<=h_pos.right){
ele.style.backgroundColor= "rgba(0,0,0,0.5)";
}else{
ele.style.backgroundColor= "#af4b23";
};
}
var display = function()
{
//console.log("done");
hea[0].style.display="inline-block";
hea[1].style.display="none";
}
var hide = function()
{
//console.log("done hiden");
hea[0].style.display="none";
hea[1].style.display="inline-block";
}
body.addEventListener("mousemove",function(){ move(event) },false);
body.addEventListener("mouseout",display,false);
body.addEventListener("mouseover",hide,false);
})();
in this answer i set background-color after setting left and top of ele. also i have removed two last eventListeners.
Look at the result online and change it yorself!
the border is added to detect h2's bounds.

Javascript global variables not changing?!

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>

Categories

Resources