Unable to generate multiple Images - javascript

This is a game where 5 more images is to be added every time when a user click on last node of left side div.
If he clicks on some other node alert 'game over' should be displayed.
Issues:
TypeError: leftside.lastChild is null
How would I delete all nodes of both the right and left hand side div before calling the generateface function to generate new set of faces.
Matching Game
click on the extra smiling face on the left
.smile {position:absolute}
div {position:absolute; width:500px;height: 500px}
#rightside {left:500px;border-left: 1px solid black}
var numberOfFaces = 5;
var leftside = document.getElementById("leftside");
var rightside = document.getElementById("rightside");
function generatefaces() {
for (i=0;ievent.stopPropagation();
numberOfFaces += 5;
generateFaces();
};
theBody.onclick = function gameOver() {
theBody.onclick = null;
alert("Game Over!");
};

You forgot to add px to the top and left style property.
Change the code as below
ismile.style.top = topran + 'px';
ismile.style.left = leftran + 'px';
var numberOfFaces = 5;
var leftside = document.getElementById("leftside");
function generatefaces() {
for (i=0;i<=numberOfFaces;i++) {
ismile = document.createElement("img");
ismile.src = "http://orig00.deviantart.net/449c/f/2009/061/5/7/smiley_icon_by_emopunk23.jpg";
ismile.className = "smile";
var topran = Math.random() * 400;
topran = Math.floor(topran);
var leftran = Math.random() *400;
leftran = Math.floor(leftran);
ismile.style.top = topran + 'px';
ismile.style.left = leftran + 'px';
leftside.appendChild(ismile);
}
}
.smile {position:absolute}
div {position:absolute; width:500px;height: 500px}
#rightside {left:500px;border-left: 1px solid black}
<body onload="generatefaces()">
<h1> Matching Game </h1>
<p> click on the extra smiling face on the left </p>
<div id="leftside"></div>
<div id="rightside"></div>
</body>

Related

How do you not have pictures on top of each other if they're part of a for loop?

im making a face matching game that one side has more than the other side and you click on the extra to play but the faces are all under one face on one side of the screen.did i miss place the 'face' element? on the browser it says 'Uncaught TypeError: leftSideImages.node is undefined' and '404 not found'
<body onload="generateFaces()">
<h1>
matching game
</h1>
<p>'Click on the extra smiling face on the left.'</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
let numberOfFaces = 5;
const theLeftSide = document.getElementById("leftSide");
const theRightSide = document.getElementById("rightSide");
function generateFaces(){
for(let i = 0; i < numberOfFaces; i++){
const face = document.createElement('img');
face.src = 'image/smile.png';
let randomTop = Math.floor(Math.random( 1 * 400)+1);
let randomLeft = Math.floor(Math.random( 1 * 400)+ 1);
face.style.top = randomTop;
face.style.left = randomLeft;
theLeftSide.appendChild(face);
}
const leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.node.removeChild(theLeftSide.theRightSide);
leftSideImages.appendChild(theLeftSide.theRightSide(true));
}
</script>
Your almost there, I think this is what you want.
You have accouple issues. The first is your JS error. To fix it I modified your code slightly. First, I split your function into two. generateFacesInDOM handles adding the dom, while generateFaces will tell where and how much, ultimately relying on generateFacesInDOM. I'm also moved the initial function call from the body tag to JS, so all your JS code is in one place.
I updated your random number to pick a random number between 0 and 100 and then set top and left as a %. Then using CSS we can allow them to position be correctly.
let numberOfFaces = 5;
var theLeftSide, theRightSide;
window.onload = () => {
theLeftSide = document.getElementById("leftSide");
theRightSide = document.getElementById("rightSide");
generateFaces();
}
function generateFaces() {
generateFacesInDOM(theLeftSide, numberOfFaces + 1);
generateFacesInDOM(theRightSide, numberOfFaces);
}
function generateFacesInDOM(parent, faces) {
for (let i = 0; i < faces; i++) {
const face = document.createElement('img');
face.src = 'image/smile.png';
//random number between 0 and 100
let randomTop = Math.floor(Math.random() * 100);
let randomLeft = Math.floor(Math.random() * 100);
face.style.top = randomTop + '%';
face.style.left = randomLeft + '%';
parent.appendChild(face);
}
}
.board {
width: 100%;
height: 200px;
/*Use the grid to make the elements appear side
by side rather than above and below*/
display: grid;
grid-template-columns: 50% 50%;
}
#leftSide,
#rightSide {
position: relative;
}
#leftSide img,
#rightSide img {
position: absolute;
}
<h1>matching game</h1>
<p>'Click on the extra smiling face on the left.'</p>
<div class="board">
<div id="leftSide"></div>
<div id="rightSide"></div>
</div>

lastElementChild returns null

I'm working on a Javascript assignment that splits the page into two div elements then appends the div on the left with randomly placed images, then I used .cloneNode() to duplicate on the right, minus the last child image.
That part of it works fine, but I am then supposed to add an event handler to the last element of the left div, but when I try to do this the lastElementChild() method returns null even though the div has the expected child nodes. The code is below and I've commented where the problem is. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
<style>
img {position: absolute}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
<script>
<!-- everything here works fine -->
function generateFaces(){
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++){
var random_x = Math.random()*400;
var random_y = Math.random()*400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
}
</script>
</head>
<body onload = "generateFaces()">
<h1> Game </h1>
<p> Instructions </p>
<div id = "right"></div>
<div id = "left"> </div>
<script>
<!-- problem script here -->
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // returns null
</script>
</body>
</html>
The body's onload event will not fire until after the javascript in your 'problem script' runs.
The order of execution here is basically:
h1, p, #left, and #right get appended to the DOM
script #1 runs, logging the empty #left div and the null lastElementChild.
body onload event fires and script #2 runs (the generateFaces() function). At this point, the <img> tags are inserted into the DOM.
The fix is to make sure that script #1 runs after #2:
<body onload="handleLoad()">
and the JS:
function handleLoad() {
generateFaces()
logStuff()
}
function logStuff() {
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // logs <img>
}
It might appear, in the console, that #left has images in it at the time that script #1 runs. This is just a quirk of the console; the actual logging happens asynchronously, and since the referenced variable changes in the meantime, the value actually logged is different than what it was when console.log() was called.
You can see this behavior by varying a setTimeout duration on the generateFaces() function call:
function generateFaces() {
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++) {
var random_x = Math.random() * 400;
var random_y = Math.random() * 400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style", "top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
}
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // returns null
setTimeout(generateFaces, 250) // play with this value
img {
position: absolute
}
div {
position: absolute;
height: 500px;
width: 500px
}
#right {
border-left: solid black;
left: 500px
}
<h1> Game </h1>
<p> Instructions </p>
<div id="right"></div>
<div id="left"> </div>
Oh, and note that your generateFaces() function currently creates multiple elements in the DOM with the same id. You're gonna want to fix that.
Your generateFaces() function is called when the body is loaded.
but your second script runs when the window is loaded.
So when the second script runs there is no temp.lastElementChild and you get null.
You can slove is like this
<!DOCTYPE html>
<html>
<head>
<style>
img {position: absolute, height: 30px; width: 30px;}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
</head>
<body onload = "generateFaces()">
<h1> Game </h1>
<p> Instructions </p>
<div id = "right"></div>
<div id = "left"> </div>
<script>
function generateFaces()
{
console.log('y');
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++){
var random_x = Math.random()*400;
var random_y = Math.random()*400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
loaded();
}
<script>
function loaded() {
var temp = document.getElementById("left");
console.log(temp);
var temp2 = temp.lastElementChild;
console.log(temp2);
}

Matching Game. Javascript. DOM lastChild

There is a simple game. The left and right sides are identical, except for one thing: the left side has one extra face. The user needs to find out and click on that extra face (lastChild). It will trigger the function to double the face quantity.
The problem is - all the faces in my game are lastChild. Where is the problem?
Thanks!
<!DOCTYPE <!DOCTYPE html>
<html>
<head>
<title>Matching Game. Part 3.</title>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
</style>
<script>
function generateFaces(){
var numberOfFaces = 5;
//var theLeftSide = document.getElementById("leftSide");
for(var i=0; i < numberOfFaces; i++) {
var smileImage = document.createElement("img");
smileImage.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var topPosition = Math.floor(Math.random()* 400) + 1;
var leftPosition = Math.floor(Math.random()* 400) + 1;
smileImage.style.top = topPosition + "px";
smileImage.style.left = leftPosition + "px";
leftSide.appendChild(smileImage);
var leftSideImages = leftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
rightSide.appendChild(leftSideImages);
leftSide.lastChild.style.background = "red";
var theBody = document.getElementsByTagName("body")[0];
leftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
numberOfFaces += 5;
generateFaces();
}
}
}
</script>
</head>
<body onload = "generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
You are binding your click event to every element in the loop. You first need to over-ride the previous handler and then re-bind it to the last element.
function generateFaces(){
var numberOfFaces = 5;
var leftSide = document.getElementById("leftSide");
var rightSide = document.getElementById("rightSide");
for(var i=0; i < numberOfFaces; i++) {
var smileImage = document.createElement("img");
smileImage.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var topPosition = Math.floor(Math.random()* 400) + 1;
var leftPosition = Math.floor(Math.random()* 400) + 1;
smileImage.style.top = topPosition + "px";
smileImage.style.left = leftPosition + "px";
leftSide.appendChild(smileImage);
var leftSideImages = leftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
rightSide.appendChild(leftSideImages);
leftSide.lastChild.style.background = "red";
var theBody = document.getElementsByTagName("body")[0];
}
var pics = document.getElementsByTagName("img");
for(i=0;i<pics.length;i++){
pics[i].onclick = function() {
return false;
}
}
leftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
numberOfFaces += 5;
generateFaces();
}
}
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
<body onload = "generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>

Using on click vanilla JS, activating on wrong node

Almost finished this sort of game i am working on to learn Dom manipulation. Basically the game spawns 5 images on the left and 4 on the right, you click the odd one out and then 10 spawn on the left and 9 on the right(+5 everytime).
I am wanting my nextlevel function to work every time the last child(of theLeftSide) is clicked on. It works the first time but after that regardless of if i click the correct node or not, my gameOver function is called and im not sure why. I tried removing the game over function and still the 2nd time i want my nextLevel to run(after click), it doesnt. Am i going about this the totally wrong way? Any input is appreciated thank you. Left my gameOver function in so you can see what im trying to do with it.
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
var facesNeeded = 5;
var totalfFaces = 0;
var theBody = document.getElementsByTagName("body")[0];
function makeFaces() {
while (facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces) {
//alert(facesNeeded);
//alert(totalfFaces);
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
}
makeFaces();
function delFaces(side) {
while (side.firstChild) {
side.removeChild(side.firstChild);
}
}
theLeftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
delFaces(theRightSide);
delFaces(theLeftSide);
totalfFaces = 0;
facesNeeded += 5;
//alert(facesNeeded);
//alert(totalfFaces);
makeFaces();
};
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
</head>
<body>
<h1> Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftside"></div>
<div id="rightside"></div>
<script src="script3.js"></script>
</body>
</html>
You just need to move the onclick inside the makeFaces after the while, so its added everytime after it creates them all:-
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
var facesNeeded = 5;
var totalfFaces = 0;
var theBody = document.getElementsByTagName("body")[0];
function makeFaces() {
while (facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces) {
//alert(facesNeeded);
//alert(totalfFaces);
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
theLeftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
delFaces(theRightSide);
delFaces(theLeftSide);
totalfFaces = 0;
facesNeeded += 5;
//alert(facesNeeded);
//alert(totalfFaces);
makeFaces();
};
}
makeFaces();
function delFaces(side) {
while (side.firstChild) {
side.removeChild(side.firstChild);
}
}
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
</head>
<body>
<h1> Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftside"></div>
<div id="rightside"></div>
<script src="script3.js"></script>
</body>
</html>

Javascript: Memory efficient way to do this effect

I wrote the code in Javascript but any good alternative would do.
EFFECT: onmousemove over the webpage circles of random colors should create wherever the mouse moves. and they have to be added behind a mask image(circles are visible only in the transparent portion of the image which is a logo. thus creating a color paint to create logo onmousemove.
it doesn't work in jsfidde because of its memory intensiveness.
WORKING LINK: http://goo.gl/DNRxO9
I pasted the exact code you can create a new html file with the following code and IT WORKS PERFECT IN FIREFOX ONLY because of its memory intensiveness(lots of divs added in very short time so DOM becomes very very heavy).
<html>
<head>
<style type="text/css">
body{
padding:0;
margin:0;
overflow: hidden;
}
#mask{
width:100%;
height:auto;
position:absolute;
z-index:10;
}
#logo{
width:50%;
height:50%;
margin:auto;
}
.point{
width:0px;
height:0px;
background-color:#ff0000;
position:absolute;
z-index:5;
left:50px;top:50px;
border-width:50px;
border-style: solid;
border-color:red;
border-radius:50px;
opacity:1;
transition: border-width 3s ease-in-out;
}
.no-border{border-width:0px;}
</style>
<script type="text/javascript">
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
/* OptionalCode: for removing divs after a lot are created */
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
i=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
var point = document.getElementsByClassName('point');
document.body.innerHTML += "<div class='point'></div>";
point[i].style.borderColor = getRandomColor();
//point[i].className += ' no-border';
point[i].style.left = x + 'px';
point[i].style.top = y + 'px';
i++;
}
function position(){
var ht = window.getComputedStyle(document.getElementById("mask"), null).getPropertyValue("height");
var ht_num = Number(ht.slice(0,ht.length - 2));
margin_top = (Number(document.body.clientHeight) - ht_num)/2;
document.getElementById('mask').style.marginTop = margin_top + "px";
}
</script>
</head>
<body onload="position();" onmousemove="colors(event)">
<img id="mask" src="http://goo.gl/EqfJ0L">
</body>
</html>
There is one HUGE, HUGE, HUGE performance killer in your code:
document.body.innerHTML += "<div class='point'></div>";
This takes your entire document, throws it away and just inserts everything back again. This is horrible! Remember this for all times and never do this again! ;)
Keep the basic rule in mind, to never add Elements via .innerHTML!
The correct way to go is the following:
// create your new div element
var circleElement = document.createElement("div");
// add all the stuff needed
circleElement.classList.add("point");
circleElement.style.borderColor = getRandomColor();
circleElement.style.left = x + 'px';
circleElement.style.top = y + 'px';
// now append the element to the body
document.body.appendChild(circleElement);
This creates a single div and nicely inserts it as a child-element of the body.
Additionally you can decrease the number of divs drawn by introducing a threshhold:
var lastX=0,lastY=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
if (Math.abs(lastX - x) + Math.abs(lastY - y) <= 10 ) return;
/* do stuff */
lastX = x;lastY = y;
}
As a third measure you can decrease the size of the image to just hold the mask element and trigger the mousemove only on the image (because divs outside the mask are hidden anyway).
Ultimately, you could kill "old" div-elements when you have reached a certain amount.
I have not included these two last optimizations, but look at the already supersmooth example now!

Categories

Resources