Creating <div> grid with JQuery for loop - javascript

I'm new to web development but have a pretty solid programming background. I've tried multiple ways to create a element programatically based on user input. I'm trying to essentially create a grid through JQuery.
I'm tackling this problem by storing the user input into a variable and going through a for loop to create the grid. Here is the code for the .js file:
var rows = 8;
var columns = 8;
var $row = $("<div />", {class: 'row'});
var $square = $("<div />", {class: 'square'});
$(document).ready(function(){
for(var i = 0; i < rows; i++){
$("#wrapper").append($row);
}
for(var i = 0; i < columns; i++){
$(".row").append($square);
}
});
Now for some reason, this code only creates one row in #wrapper and one square in the row. I've tried copying the example CSS files that tackle this problem but nothing seems to work. Here's what I have right now for my CSS:
#wrapper {
width: 850px;
height: 850px;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background: #000000;
}
.row {
width: auto;
height: 100px;
background: #313131;
}
.square {
width: 100px;
height: 100px;
margin: 0px;
outline: 1px solid;
display: inline-block;
float: left;
background: #FFFFFF;
}
And here's my HTML:
<!doctype html>
<html>
<head>
<title>Draw Grid</title>
<link rel="stylesheet" type="text/css" href="theme.css" >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="draw.js"></script>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>
Can anybody help me out? I'm so confused. I've tried everything. Is this a CSS formatting error?

The problem is you are creating only one row and square objects, you need to use cloned copies else they are just copy
var rows = 8;
var columns = 8;
var $row = $("<div />", {
class: 'row'
});
var $square = $("<div />", {
class: 'square'
});
$(document).ready(function () {
//add columns to the the temp row object
for (var i = 0; i < columns; i++) {
$row.append($square.clone());
}
//clone the temp row object with the columns to the wrapper
for (var i = 0; i < rows; i++) {
$("#wrapper").append($row.clone());
}
});
Demo: Fiddle

Related

How to add buttons dynamically in grid format (rows and columns) using javascript?

I need to display the buttons dynamically in a row (with small space between buttons) based on the response from one server. If the buttons cross the screen, need to display the buttons in the next row. I thought of using table as below.
<!DOCTYPE html>
<html>
<head>
<style>
td {
width: 200px;
height: 200px;
}
button {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<p>Table with cellspacing:</p>
<table cellspacing="50">
<tr>
<td><button id='b1' onclick='clickbt("b2")'>Month</button></td>
<td><button id='b2' onclick='clickbt("b3")'>Savings</button></td>
</tr>
<tr>
<td><button id='b3' onclick='clickbt("b4")'>January</button></td>
<td><button id='b4' onclick='clickbt("b1")'>$100</button></td>
</tr>
</table>
<script>
function clickbt(id) {
document.getElementById(id).focus();
}
</script>
</body>
Even though the code is creating buttons, I am hardcoding it two buttons per row and I am hardcoding columns as 2.
But as I need to create the buttons dynamically based on the response from the server, Is there any solution using javascript instead of static rows and columns in html?
You can use JS and CSS to solve your problem.
With JS you can create and append any amount of elements you need.
I made a small snippet to mock this. The var buttonsToGenerate should be replaced dynamically based on the response from the your server
With CSS you can use flexbox layout to make a more dynamic and most important, responsive layout
Hope this helps :)
function generate(){
let buttonsToGenerate = Math.floor(Math.random() * (3)) + 1;
for(let i = 0; i < buttonsToGenerate; i++){
var btn = document.createElement("button");
var t = document.createTextNode("button text");
btn.appendChild(t);
document.getElementById('button-holder').appendChild(btn);
}
}
p {
display: inline;
}
p + button {
width: auto;
height: auto;
}
button {
width: 200px;
height: 200px;
}
#button-holder {
display: flex;
width: 100%;
height: auto;
flex-wrap: wrap;
justify-content: space-between;
}
<!DOCTYPE html>
<body>
<p>This will generate buttons between 1 - 5 per click:</p><button onclick="generate()">RUN</button>
<div id="button-holder"></div>
<script>
</script>
</body>
This is an example of creating dynamic buttons for a table. In this example you set number of buttons and number of buttons on each row.
var buttonNum = 10,
w = window.innerWidth,
rowButtonNumber = Math.floor(w / 200);
var table = document.getElementById("myTable");
for (var i = 0; i < buttonNum; i++) {
var tr = document.createElement("tr");
table.appendChild(tr);
for (var j = 0; j < rowButtonNumber; j++, i++) {
var td = document.createElement("td");
var btn = document.createElement("button");
btn.innerHTML = "btn " + (i + 1);
btn.id = "btn-" + i;
btn.onclick = function () { alert(this.innerHTML); };
if (i >= buttonNum) {
break;
} else {
td.appendChild(btn);
tr.appendChild(td);
}
}
i--;
}
<html>
<head>
<style>
td {
width: 200px;
height: 200px;
}
button {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<p>Table with cellspacing:</p>
<table id="myTable" cellspacing="50">
</table>
<script>
function clickbt(id) {
document.getElementById(id).focus();
}
</script>
</body>

Create dynamic Rectangle collection in html using js

Hello All I am a beginner in html and js, and I am trying to create a webpage containing a rectangle collection in which when a new rectangle is created is placed beside the previous rectangle.
I have created a div element and trying to add newly created div (rectangle shape with background color different based on condition), but I am not able to get the desired result.
<html>
<head>
<title>parkIn</title>
<meta charset="utf-8" />
</head>
<style>
.ParkSlots {
border: solid 1px;
width: 60%;
height: 400px;
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
display: inline;
}
.row:before,
.row:after {
content: "";
display: table;
clear: both;
}
.col-1 {
width: 15%;
margin-left: 10px;
height: 350px;
padding: 2px;
}
</style>
<body onload="viewCreate()">
<div class="ParkSlots">
<div class="row" id="content">
</div>
</div>
</body>
<script language="javascript">
function viewCreate() {
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
createGreenBox();
} else {
createRedBox();
}
}
}
function createRedBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'red';
document.getElementById('content').appendChild(div);
}
function createGreenBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'lightgreen';
document.getElementById('content').appendChild(div);
}
</script>
</html>
I want an output that looks something like this:
Just in glancing at your code, I see at least two typos:
for (int i = 0; i < 5; i++) { - in JS, int is not used in this way. Use var i = 0...
var = document.createElement('div'); - you're missing a variable name on this line in both create box functions. I assume, from the rest of the code you need var div = document.createElement('div');
The rest will be CSS. In your stylesheet you're applying the border to the outter most containing div, from you're example, you need to apply that to the .col-1 class. You'll also want to use display:inline-block on that class, and set widths and margins to play nicely with the border size. I took the liberty of creating a jsfiddle for you with my recommended changes.

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>

Trying to create a 16x16 grid of divs using jQuery but divs keep overlapping

I'm doing a small project for an online course and I need to create a 16x16 grid of divs using jQuery to manipulate the DOM. Problem is, the divs are overlapping, how do I fix this? I'm a beginner so please be very critical of my work, it would be a huge help, thanks.
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="EASP.css">
<head>
<title></title>
</head>
<body>
<div id="container"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="EASP.js"></script>
</body>
</html>
#container {
background-color: red;
height: 192px;
width: 192px;
}
.unit {
background-color: blue;
height: 10px;
width: 10px;
margin: 1px;
display: inline-block;
}
$(document).ready(function() {
var unit = $("<div class='unit'></div>");
for(var x = 0; x < 2 x++) {
for(var y = 0; y < 2; y++) {
unit.appendTo('container');
}
}
});
Problems are:
The CSS selector should be #container since you are referring it
by ID.
Also, there is missing a semicolon in your first loop
And, div.unit should be defined inside the second for as in every loop you want to add a new DIV element:
After applying those changes, this code should work:
$(document).ready(function() {
for(var x = 0; x < 16; x++) {
for(var y = 0; y < 16; y++) {
var unit = $("<div class='unit'></div>");
unit.appendTo('#container');
}
}
});
See JSFiddle demo
Here is a working example. And here is just the code:
HTML
<div id="container"></div>
CSS
#container {
background-color: red;
height: 192px;
width: 192px;
}
.unit {
background-color: blue;
height: 10px;
width: 10px;
margin: 1px;
float: left;
}
jQuery
$(function() {
for (var x = 0; x < 16; x++) {
for (var y = 0; y < 16; y++) {
$("<div>").addClass("unit").appendTo("#container");
}
}
});
The elements are not overlapping. What happened is that you only created one and appended it to the container twice in the loop. Naturally, only one shows up because only one was made.
Create and append the in the for loop.
You must also fix some syntax errors in your original code:
$(document).ready(function() {
for(var x = 0; x < 2; x++) {
for(var y = 0; y < 2; y++) {
var unit = $("<div class='unit' style='position:absolute'></div>");
unit.appendTo('#container', {left: });
}
}
});
Seeing how you have a nested loop, I assume you are trying to make a grid matrix. This code will not make a x by y grid because of the floating and collapsing of the html elements. To properly create a grid, you must specify the x and y position using a absolute positioning style and multiply the count by the width. It really depends though because you can just as easy fill up your main container without doing this as well.

JQuery. Facing problems with click events

I was writing code for image flip game in jquery but I am facing some problems with the click events on image in the beginning. The problems are when I click one image and click again the same image it works fine but if I click one image, the image src attribute is added to the img tag and then if I click any other image the src attribute is not added to that one for the first click because the clickCounter has the value 1 then. I employed my own logic (clickCounter). I am new to jquery. You may suggest a better way to do this. Thanks in advance.
Here is my code.
<style>
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
</style>
<body>
<div id="main">
</div>
<button id="add">Add</button>
<script src="jquery-1.11.2.js"></script>
<script>
var clickCounter = 0;
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
if(clickCounter == 0){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
clickCounter = 1;
}else{
myImage.removeAttr('src');
clickCounter = 0;
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
</script>
</body>
JSFiddle
The problem is the shared variable clickCounter which is shared between all the elements.
In this case since you have dynamic elements, you could use event delegation and then use the current src value of the img to set the new one like
$('#add').click(function () {
addElements(44);
$('#add').prop('disabled', true);
});
$('#main').on('click', '.myimg', function () {
$(this).attr('src', function (i, src) {
return src == 'back.png' ? '' : 'back.png';
}).height(100).width(100);
})
function addElements(times) {
var $main = $('#main');
for (j = 1; j <= times; j++) {
$('<img />', {
'class': 'myimg'
}).appendTo($main)
}
}
Demo: Fiddle
Instead of counter, check for 'src' attribute as shown below,
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
var attr = $(this).attr('src');
if(typeof attr == typeof undefined){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
}else{
myImage.removeAttr('src');
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
</div>
<button id="add">Add</button>

Categories

Resources