JQuery Picture Memory Game - javascript

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.

Related

Trying to generate 100 boxes but only 2 boxes are displayed?

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)

Colored Squares HTML/Javascript

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>

How to populate browser's entire window/document with rectangles

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);
}
}

Simple JavaScript DOM manipulation

Could anyone please tell me what is wrong with this code? I am trying to create a table from stratch and add ten rows and cells to it. Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
var cargar = function () {
var tabla = document.createElement("TABLE");
document.body.appendChild(tabla);
var cebreado = function () {
console.log("Inicio" + a);
for (var a = 0; a > 10; a++) {
tabla.appendChild(document.createElement("TR"));
console.log("Hola" + a);
for (var b = 0; b > 10; b++) {
tabla.appendChild(document.createElement("TD"));
}
}
}
;
return cebreado;
}
;
</script>
</head>
<body onload="cargar()">
</body>
</html>
You got a couple of things wrong:
You do not call the function cebreado, you simply refer to it
Both you for loops had > when it shold be <
You were not appending the TD into TR, but to the table itself.
Here is your code working:
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
var cargar = function () {
var tabla = document.createElement("TABLE");
document.body.appendChild(tabla);
var cebreado = function () {
console.log("Inicio" + a);
for (var a = 0; a < 10; a++) {
tabla.appendChild(document.createElement("TR"));
console.log("Hola" + a);
for (var b = 0; b < 10; b++) {
tabla.lastChild.appendChild(document.createElement("TD"));
}
}
}
;
return cebreado();
}
;
</script>
</head>
<body onload="cargar()">
</body>
</html>
try this : http://jsfiddle.net/mig1098/nt3sd8dw/
var cargar = function () {
var tabla = document.createElement("TABLE");
document.body.appendChild(tabla);
var cebreado = function () {
for (var a = 0; a < 10; a++) {
console.log("Inicio" + a);
var tr = document.createElement("TR");
tabla.appendChild(tr);
console.log("Hola" + a);
for (var b = 0; b < 10; b++) {
var td = (document.createElement("TD"));
tr.appendChild(td);
var text = document.createTextNode("Hello");
td.appendChild(text);
}
}
}
;
return cebreado();
}
;
cargar();
Miglio answered it already.
What you can do, too, is change onload="cargar()" to onload="cargar()()"
Example:
function cargar() {
function cebreado() {
alert("x");
}
return cebreado;
}
cargar()();
The final behaviour will be the same, but they are different things.

onkeyup event on dynamic array

Good Evening,
I am having trouble setting up the onkeyup event. I am trying to get it to fire an objects method when a user enters text into the text field. It does not seem to find the object.
I have cut down on the code and have made the following sample:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var ReportModule = new function () {
function ReportObj(id, title) {
this.id = id;
this.title = title;
this.result = "";
this.empno = "";
this.UpdateEmpno = function (empNo, resultBoxID) {
this.empno = empNo;
$(resultBoxID).update("Result: " + empNo);
};
};
var ReportObjArray = new Array();
var test1 = new ReportObj("box1", "First object");
var test2 = new ReportObj("box2", "Second object");
ReportObjArray.push(test1);
ReportObjArray.push(test2);
this.Initialize = function () {
for (i = 0; i < ReportObjArray.length; i++) {
var container = document.createElement("div");
container.id = ReportObjArray[i].id;
container.textContent = ReportObjArray[i].title;
$('#Container').append(container);
var empnoInput = document.createElement("input");
empnoInput.type = "text";
empnoInput.id = ReportObjArray[i].id + "_Empno";
empnoInput.onkeyup = function (event) {
// Update Report Objects empno field
ReportObjArray[i].UpdateEmpno(empnoInput.value,empnoInput.id); // <-------- Undefined here
};
$('#' + ReportObjArray[i].id).append(empnoInput);
var container2 = document.createElement("div");
container2.id = ReportObjArray[i].id + "_result";
container2.style.border = "1px solid black";
container2.style.width = "100px";
container2.textContent = "Result:";
$('#' + container.id).append(container2);
};
};
}
</script>
</head>
<body onload="ReportModule.Initialize()">
<div id="Container"></div>
</body>
</html>
Update: It works when searching for the object in the ReportObjArray and matching the correct object. However, I was wondering if there was a more efficient way instead of having to look through the array each time.
empnoInput.onkeyup = function (event) {
// Update Report Objects empno field
var target_id = document.getElementById(event.target.id).id;
for (j = 0; j < ReportObjArray.length; j++) {
if (target_id = ReportObjArray[j].id) {
ReportObjArray[j].UpdateEmpno(document.getElementById(event.target.id).value,empnoInput.id);
break;
}
}
};
Wrap your for loop code in a closure:
for (i = 0; i < ReportObjArray.length; i++) {
(function(i) {
// code
})(i);
}
Working JS Fiddle:
http://jsfiddle.net/23vkS/

Categories

Resources