So I'm only using javascript, html, and css to generate 100 boxes in any random position, this works by using the div with the id container in the html file and then using the javascript file to generate the boxes through a loop making a div for each box then appending it to the container, but the problem is I can see two boxes appearing on screen? here is my code below:
//this is the javascript
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.setAttribute("id", "box");
container.appendChild(box);//o
var bx = document.getElementById("box");
var w=window.innerWidth;
var h=window.innerHeight;
bx.style.right = w * Math.random() + "px";
bx.style.top = h * Math.random() + "px";
}
}
//here is the css
#box
{
background-color: blue;
width: 50px;
height: 50px;
padding: 5px;
position: fixed;
}
//this is the html
<!DOCUTYPE html>
<html lang = "en">
<head>
<link href = "box.css" rel = "stylesheet" type="text/css">
<script src = "box.js" type="text/javascript"></script>
</head>
<body onload="myFunction()">
<div id="container">
</div>
</body>
</html>
Don't get a reference for the box again from the DOM
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.setAttribute("id", "box");
container.appendChild(box);//o
// var bx = document.getElementById("box"); <--- this line is redundant
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
ID's should be unique, instead use a class for each box
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.classList.add("box");
container.appendChild(box);//o
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
So your code in the end becomes:
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.classList.add("box");
container.appendChild(box);//o
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
.box
{
background-color: blue;
width: 50px;
height: 50px;
padding: 5px;
position: fixed;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<link href = "box.css" rel = "stylesheet" type="text/css">
<script src = "box.js" type="text/javascript"></script>
</head>
<body onload="myFunction()">
<div id="container">
</div>
</body>
</html>
Use the name attribute and a data-id attribute to retrieve any elements with an unique id.
Construction:
let container = document.getElementById("container")
for(let count = 1; count < 100; ++count) {
let box = document.createElement("DIV")
box.setAttribute("name", "e")
box.dataset.id = count
container.appendChild(box)
}
HTML result :
<div name="e" data-id="1"></div>
<div name="e" data-id="2"></div>
<div name="e" data-id="3"></div>
<div name="e" data-id="4"></div>
Add a function to retrieve any element with the first occurence of a numbered id.
function getFormRef(name, id) {
let d = document.getElementsByName(name)
let x = Array.prototype.slice.call(d).filter(a => a.dataset.id == id)
return x[0]
}
let first = getFormRef("e", 1)
Related
Here is the current index (HTML and JavaScript):
var maxZ = 1000;
window.onload = function() {
var add = document.getElementById("add");
add.onclick = addSquare;
var colors = document.getElementById("colors");
colors.onclick = changeColors;
var squareCount = parseInt(Math.random() * 21) + 30;
for (var i = 0; i < squareCount; i++) {
addSquare();
}
}
//Generates color
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function addSquare() {
var square = document.createElement("div");
var squareArea = document.getElementById("squareArea");
square.className = "square";
square.style.left = parseInt(Math.random() * 650) + "px";
square.style.top = parseInt(Math.random() * 250) + "px";
square.style.backgroundColor = getRandomColor();
square.onclick = squareClick;
squareArea.appendChild(square);
}
function changeColors() {
var squares = document.querySelectorAll("#squareArea div");
for (i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = getRandomColor();
}
}
function squareClick() {
var oldZ = parseInt(this.style.zIndex);
if (oldZ == maxZ) {
this.parentNode.removeChild(this);
} else {
maxZ++;
this.style.zIndex = maxZ;
}
}
<html>
<head>
<title>Colored Squares</title>
<script src="Squares.js" type="text/javascript"></script>
<link href="Squares.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="squareArea"></div>
<div>
<button id="add">Add Square</button>
<button id="colors">Change Color</button>
</div>
<p>Click a square to move it to the front.</p>
</body>
</html>
Here is the goal:
Edit Colored squares to add the following functionality.
Users will be able to click a square and drag it to any position on the screen. - When the user lets go of the click it will stay in that position.
In order to accomplish this you will need to add Prototype and Scriptaculous to the scripts loaded in the html and use their functionality.
You will also need to create 3 functions in the JavaScript file:
function squareMouseMove(event)
function squareMouseDown(event)
function squareMouseUp(event)
Add appropriate global variables
Change the creation of the squares to added observers for the mouse events that execute the functions.
The issue that you have with your code is that the squares are empty, so they collapse to nothing and you will not see them. Add a width and height to them so you can see them.
Another issue is that you're specifying the left and right, but these properties will have no effect unless you make them absolutely positioned.
Here is your code working with the width, height, and position properties added:
var maxZ = 1000;
window.onload = function() {
var add = document.getElementById("add");
add.onclick = addSquare;
var colors = document.getElementById("colors");
colors.onclick = changeColors;
var squareCount = parseInt(Math.random() * 21) + 30;
for (var i = 0; i < squareCount; i++) {
addSquare();
}
}
//Generates color
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function addSquare() {
var square = document.createElement("div");
var squareArea = document.getElementById("squareArea");
square.className = "square";
square.style.left = parseInt(Math.random() * 650) + "px";
square.style.top = parseInt(Math.random() * 250) + "px";
square.style.width = "100px";
square.style.height = "100px";
square.style.position = "absolute";
square.style.backgroundColor = getRandomColor();
square.onclick = squareClick;
squareArea.appendChild(square);
}
function changeColors() {
var squares = document.querySelectorAll("#squareArea div");
for (i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = getRandomColor();
}
}
function squareClick() {
var oldZ = parseInt(this.style.zIndex);
if (oldZ == maxZ) {
this.parentNode.removeChild(this);
} else {
maxZ++;
this.style.zIndex = maxZ;
}
}
<html>
<head>
<title>Colored Squares</title>
<script src="Squares.js" type="text/javascript"></script>
<link href="Squares.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="squareArea"></div>
<div>
<button id="add">Add Square</button>
<button id="colors">Change Color</button>
</div>
<p>Click a square to move it to the front.</p>
</body>
</html>
My question is as follows, how could I pass images that are inside an array to a div?
I've multiplied the div#imagem and I need to pass the array images to it.
But I do not know how.. Can someone help me?!
My JavaScript/JQuery
var divBoard = $("<div id='board'></div>");
$("body").after(divBoard);
var titleGame = $("<h1></h1>").text("Memory Game");
var btnReset = $("<input id='btn-reset' type='button' onclick='reset()' value='Reset'>");
$("#board").append(titleGame);
$("#board").append(btnReset);
(function (){
var images = ['img/facebook.png','img/android.png','img/chrome.png','img/firefox.png','img/html5.png','img/googleplus.png','img/twitter.png','img/windows.png','img/cross.png'];
$(window).load(function () {
$('#board').html('');
var numCards = 16;
for (var i = 1; i <= numCards; i++) {
$("#board").append("<div class='image" + i + " images'></div>") &&
$(".image" + i).clone().appendTo("#board");
}
var cards = $(".images");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
}
})();
app.start();
});
My HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<title>JavaScript Memory Game</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script charset="utf8">
var app = { nrComponents:0 };
app.getComponent = function(name) {
if (!app[name]) {
app[name] = {};
app[app.nrComponents++] = name;
}
return app[name];
};
</script>
<script src="script.js" charset="utf8"></script>
</body>
</html>
Here are critical 2 problems I listed. Some line in your code seems not neccecery and hard to debug for it. I would suggest to simplify your code for better debugging.Hope it helps..
$("body").after(divTabuleiro); I think this will insert content after 'body' instead of putting 'divTabuleiro' inside the 'body'.
$("#tabuleiro").append(""); should have tag inside for insert images.
// Create a start function and move you initial code here....
app.start = function(){
var imagens = [
'https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg',
'http://www.pressunion.org/wp-content/uploads/2016/11/1-2.jpg',
'http://www.feixiubook.com/wp-content/uploads/2016/06/01-25.jpg'
];
var divTabuleiro = $("<div id='tabuleiro'></div>");
$("body").append(divTabuleiro);
var titulo = $("<h1></h1>").text("Jogo da Memória");
var btnReset = $("<input id='btn-reset' type='button' onclick='reset()' value='Reset'>");
$("#tabuleiro").append(titulo);
$("#tabuleiro").append(btnReset);
$('#tabuleiro').html('');
var numCards = 3;
for (var i = 0; i < numCards; i++) {
var img = imagens[i];
$("#tabuleiro").append("<div class='my-image-" + i + " my-image'><img src='" + img + "'></div>") && $(".my-image-" + i).clone().appendTo("#tabuleiro");
}
// randomize cards in stack
var cards = $(".my-image");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
}
};
// Maybe create another function
app.reset = function(){
};
$(window).ready(function() {
// Because you have created a start function above. you can call it when document ready
app.start();
});
.my-image {
width: 200px;
height: 200px;
overflow: hidden;
float: left;
}
.my-image img {
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// Create a namespace of app
var app = { nrComponents:0 };
// Add a function 'getComponent' in to it
app.getComponent = function(name) {
if (!app[name]) {
app[name] = {};
app[app.nrComponents++] = name;
}
return app[name];
};
// So There is no start() function inside......
// we can add start function later..
</script>
Hm.. I somehow don't understand your exact request, but for making images based on an array you can use this as a guide :
var imagens = ['img/facebook.png','img/android.png','img/chrome.png','img/firefox.png','img/html5.png','img/googleplus.png','img/twitter.png','img/windows.png','img/cross.png'];
$.each(imagens,function(index,imageSrc){
$("Parent Element").append('<img src="'+imageSrc+'" />');
});
hope it helps.
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 want to populate the entire window with rectangles, no matter what size of window it is. eg. If rectangles are 250px wide, and window is 1000px wide, then it shold be 4 rec. in one row. I managed to fill just one row. Here is the code below
<!DOCTYPE HTML>
<html>
<head>
<style>
div {
width: 250px;
height: 150px;
border: 1px solid black;
border-collapse: collapse;
display: block;
position: fixed;
}
</style>
<script>
function ubaci_div() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}
</script>
</head>
<body id="body">
<p id="p" onclick="ubaci_div()">Klikni</p>
</body>
</html>
I think you are asking for something like this?
https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/9/
function ubaci_div() {
var i = 0;
var h = window.innerHeight;
var num = (h / 150);
for (i = 0; i < num; i++) {
alert(num);
loop();
var br = document.createElement('br');
}
}
function loop() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth - 250; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}
Something like this?
JSFiddle: https://jsfiddle.net/vc7w608m/
var rectangleWidth = 250;
var rectangleHeight = 100;
var columnCount = Math.ceil(window.innerWidth / rectangleWidth);
var rowCount = Math.ceil(window.innerHeight / rectangleHeight);
console.log(columnCount, rowCount)
for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
var rowDiv = document.createElement("div");
rowDiv.style.height = rectangleHeight + "px";
rowDiv.style["white-space"] = "nowrap";
rowDiv.style["overflow"] = "hidden";
document.body.appendChild(rowDiv);
for (var columnIndex = 0; columnIndex < columnCount; columnIndex++) {
var rectangle = document.createElement("div");
rectangle.style.height = rectangleHeight + "px";
rectangle.style.width = rectangleWidth + "px";
rectangle.style.display = "inline-block";
rectangle.style["background-color"] = "rgb(" + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ")";
rowDiv.appendChild(rectangle);
}
}
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>