onclick event not running, code sequence not correct - javascript

The code below runs as far as alert("click on extra image on the left") then it does nothing upon clicking on the extra image that is added to the left div. Upon clicking on the extra image (id="extraImage") I would like JS to change the color of the "extraImage" element to red. Also, I need to change the sequence in which the code is executed and run the alert("click on extra image on the left") AFTER pictures have been added. Any thoughts greatly appreciated.
<html>
<head> </head>
<body>
<div id="containerLeft">
</div>
<div id="containerRight">
</div>
<script>
var i = 1
var pocetSmilikov = prompt("enter number of smiley faces");
alert("i will add" + pocetSmilikov);
while (i <= pocetSmilikov)
{
insert();
i++;
}
insertExtraToLeft();
function insert() {
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAdded.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
var the_node = document.getElementById("containerRight").lastChild;
var the_clone = the_node.cloneNode(true);
document.getElementById("containerLeft").appendChild(the_clone);
}
function insertExtraToLeft() {
var imgDestinationExtra = document.getElementById("containerLeft");
var imgAddedExtra = document.createElement("img");
imgAddedExtra.src = "smiley.png";
imgAddedExtra.id = "extraImage"
imgDestinationExtra.appendChild(imgAddedExtra);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAddedExtra.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
}
alert("click on extra image on the left");
extraImage.onclick = extraImgFound();
function extraImgFound() {
document.getElementById("extraImage").style.color = "red";
}
</script>
</body>
</html>

extraImage is not defined anywhere. Add imgAddedExtra.onclick = extraImgFound(); in your insertExtraToLeft() function.
Try:
function insertExtraToLeft()
{
var imgDestinationExtra = document.getElementById("containerLeft");
var imgAddedExtra = document.createElement("img");
imgAddedExtra.src = "smiley.png";
imgAddedExtra.id ="extraImage"
imgDestinationExtra.appendChild(imgAddedExtra);
imgAddedExtra.onclick = extraImgFound();
var left = Math.floor((Math.random() * 50) + 1)+"px";
var top = Math.floor((Math.random() * 50) + 1)+"px";
var imagestyle = imgAddedExtra.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
}

Related

Add scoreboard to "game"

I'm trying to make a small version of "duck hunt" I want to add a scoreboard when every time you hit the duck its +1 and when you miss its -1 but the score cant go lower than 0 (so not -1 for example) when you have tried 20 times the game stops and you will see your score so the hit and miss clicked times will show on the screen. How do I add this to my code so far I have got this:
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var hit = 0;
var miss = 0
var count = 0;
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
duck.addEventListener('click', moveduck);
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
};
button1.onclick = succesfullhit;
function succesfullhit() {
hit++;
button1.innerHTML = hit;
}
button2.onclick = failedhit;
function failedhit() {
miss--;
button2.innerHTML = miss;
}
#duck { height:50px; }
<!DOCTYPE html>
<html lang="en">
<head>
<title>Duck hunt</title>
<link rel="stylesheet" type="text/css" href="Duckhunt.css">
</head>
<body>
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" />
<button id="button1">Hit: </button>
<p></p>
<button id="button2">Miss: </button>
</div>
<script src="Duckhunt.js"></script>
</body>
</html>
I guess you want to do something like this :
i changed the hit and miss and i did only score.
i added event listener to the document, if you hit the duck score++ if not score--
and i display the score.
i added if statement, if score is === -1 game over.
if score === 20 win
Of course you need to do a bit work to make it perfect for your need, this is just for the beginning.
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var score = 0
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
score++
};
document.addEventListener("click", function(e){
if(score === -1){
score = 0
document.getElementById('score').innerHTML = 'Game over'
console.log('game over')
}
if(score === 20){
document.getElementById('score').innerHTML = 'Win'
console.log('Win')
}
if (e.target.id === 'duck'){
moveduck()
document.getElementById('score').innerHTML = score
}else {
score--
document.getElementById('score').innerHTML = score
}
})
#duck { height:50px; }
<!DOCTYPE html>
<html lang="en">
<head>
<title>Duck hunt</title>
<link rel="stylesheet" type="text/css" href="Duckhunt.css">
</head>
<body>
<div id="scoreBoard">Score: <p id="score"></p></div>
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" />
</div>
<script src="Duckhunt.js"></script>
</body>
</html>
Here is a start
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var hit = 0;
var miss = 0
var count = 0;
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
document.body.addEventListener('click', function(e) {
if (hit+miss >= 20) return
const tgt = e.target;
if (tgt.id ==="duck") succesfullhit()
else failedhit();
if (hit+miss === 20) clearInterval(timing)
else moveduck();
});
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
};
function succesfullhit() {
hit++;
button1.innerHTML = hit;
}
function failedhit() {
miss++;
button2.innerHTML = -1*miss;
}
#duck { height:50px; }
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" /><br/>
<button id="button1">Hit: </button>
<p></p>
<button id="button2">Miss: </button>
</div>

How to prevent randomly generated images from overlapping using Javascript

I'm trying to spawn randomly generated targets on the screen using a function to copy an invisible image of the target to be spawned at a random place within the screen using window object properties.
For this to happen I think the image have to have position set to absolute, but then several images may be spawned in a way that they will overlap, how can I prevent this from happening?
The div element where I copy my first image and also store the other copies.
<div id="targetsDiv">
<img src="target2.png" alt="target_shot" class="target" />
</div>
Inside the script:
var x_pixels = window.innerWidth - 180;
var y_pixels = window.innerHeight - 180;
var x_midScreen = window.innerWidth / 2;
var y_midScreen = window.innerHeight / 2;
var xRandom = Math.floor(Math.random()*x_pixels) +1;
var yRandom = Math.floor(Math.random()*y_pixels) +1;
var targetCollection = document.getElementById("targetsDiv");
var targetCopy = targetCollection.innerHTML
var targetList = document.getElementsByClassName("target");
targetList[0].style.display = "none";
var targetNr = 1;
var numberOfSpawns = 3;
function spawnTargets () {
while (targetNr <= numberOfSpawns) {
if ((xRandom < x_midScreen - 126 || xRandom > x_midScreen + 26) || (yRandom < y_midScreen - 126 || yRandom > y_midScreen + 26)) {
targetCollection.innerHTML += targetCopy;
targetList[targetNr].style.left = xRandom + "px";
targetList[targetNr].style.top = yRandom + "px";
targetNr++;
}
xRandom = Math.floor(Math.random()*x_pixels) +1;
yRandom = Math.floor(Math.random()*y_pixels) +1;
}
}
PS: I appreciate all help, tips and tweaks that you guys provide:) Thanks for helping
The area you want to exclude in the centre of the screen is rather large, and on my little laptop, there isn't even any room to still show the random positioned images.
But anyway, this piece of code should do the job -- I added some infinite loop protection which on my PC was a life-saver:
HTML (added style attribute)
<div id="targetsDiv">
<img src="target2.png" alt="target_shot" class="target"
style="visibility:hidden"/>
</div>
JavaScript:
window.addEventListener('load', function () {
var targetCollection = document.getElementById("targetsDiv");
var template = document.getElementsByClassName("target")[0];
var targetWidth = template.offsetWidth;
var targetHeight = template.offsetHeight;
var x_pixels = window.innerWidth - targetWidth;
var y_pixels = window.innerHeight - targetHeight;
var x_midScreen = window.innerWidth / 2;
var y_midScreen = window.innerHeight / 2;
function spawnTargets (numberOfSpawns) {
var targets = [];
var count = 0; // infinite recursion protection
for (var i = 0; i < numberOfSpawns; i++) {
do {
do {
var x = Math.floor(Math.random()*x_pixels);
var y = Math.floor(Math.random()*y_pixels);
if (count++ > 200) {
console.log('give up');
return;
}
} while ((x >= x_midScreen-450 && x <= x_midScreen+300) && (y >= y_midScreen-350 || y <= y_midScreen+200));
for (var j = 0; j < i; j++) {
if (x >= targets[j].x - targetWidth && x <= targets[j].x + targetWidth &&
y >= targets[j].y - targetHeight && y <= targets[j].y + targetHeight) break; // not ok!
}
} while (j < i);
targets.push({x, y});
img = document.createElement('img');
img.src = template.src;
img.setAttribute('width', targetWidth + 'px');
img.setAttribute('height', targetHeight + 'px');
img.className = template.className;
targetCollection.appendChild(img);
img.style.left = x + "px";
img.style.top = y + "px";
}
}
spawnTargets(3);
});

Javascript - setInterval() still running after clearInterval() called

I'm making a game with Javascript. I have functions for moving left, right, gravity and down. The gravity function makes the player's location go to the bottom of the screen once it goes off the platform (div). When the gravity() function is called when you are moving right (OnButtonDownr()) it stops the move up from working. What I mean is that when I go right and off the platform and then try to go up it doesn't work but I can go up before I go off the platform. When I try to go up (and it doesn't work) it has a weird effect which looks like its position is being set to 0 but moving up at the same time. My code:
HTML (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<div id='level' class='level'>
<div class='start_platform' id='plat1'></div>
<div class='platform' style='
'></div>
</div>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveup' onmousedown="OnButtonDownu (this)" onmouseup="OnButtonUpu (this)">^</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
<script type='text/javascript' src='scripts/move.js'></script>
<script type='text/javascript' src='scripts/gravity.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</html>
JS (move.js):
//move left
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
gravityCheck();
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
//move right
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
gravityCheck();
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
//move up
var elem = document.getElementById("player");
function OnButtonDownu () {
var posu = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.idu = setInterval(frameu, 5);
elem.style.bottom = 0;
function frameu() {
gravity = false;
posu++;
elem.style.bottom = posu + 'px';
}}
function OnButtonUpu (button) {
clearInterval(idu);
}
JS (gravity.js):
var gravity = true;
function gravityCheck() {
var player = parseInt(document.getElementById("player").style.left, 10) || 0;
var plat1 = parseInt(document.getElementById("plat1").style.left, 10) || 0;
var width = player - plat1;
var elem = document.getElementById("player");
var pos = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.id = setInterval(frame, 5);
function frame() {
if(width > 100 && width < 164) {
if(gravity = true) {
pos--;
elem.style.bottom = pos + 'px';
if(elem.style.bottom = 0) {
clear();
}
}
}
}
function clear() {
clearInterval(id);
}}
How do I fix this. Thanks in advance.
You may not be clearing properly. Before setting interval clear any previously set one.
if(window.idl) clearInterval(window.idl);
window.idl = setInterval(framel, 5);

Scroll then snap to top not unsnapping

I'm trying to create snap to top divs that cover the entire page and I have it working, it's just that after they snap to the top they don't unsnap and stay fixed to the top. I'm using the answer given by mu is too short from this previous question scroll then snap to top but I can't get it to unsnap.
Here's a jsbin of the code.
var h = 0;
var notif;
var notif2;
var init;
var docked = false;
function getSize() {
h = window.innerHeight;
notif = document.getElementById("notif");
notif2 = document.getElementById("notif2");
var fl = document.getElementById("floater");
init = notif.scrollTop;
notif.style.top = "" + h + "px";
var h2 = h / 2;
fl.style.marginTop = "" + h2 + "px";
notif.style.height = "" + h + "px";
var twoh = 3 * h2;
notif2.style.top = "" + h + "px";
notif2.style.height = "" + h + "px";
}
window.onscroll = function() {
if (!docked && (notif.offsetTop - document.body.scrollTop < 0)) {
console.log("in loop");
notif.style.top = 0;
notif.style.position = 'fixed';
notif2.style.marginTop = "" + h + "px";
docked = true;
} else if (docked && document.body.scrollTop <= init) {
notif.style.position = 'block';
while (notif.style.top <= h) {
var ab = Math.abs(notif.offsetTop)
var ab2 = Math.abs(document.body.scrollTop);
notif.style.top = init + 'px';
}
if (notif.style.top == h || notif.style.top == h - 1) {
docked = false;
}
}
};
<body onload="getSize()">
<div class="contain">
<div id="floater">
<h1 class="white">Hello, World</h1>
Link 1 Link 2
</div>
</div>
<div class="announcements" id="notif">
Please cover the previous text on the page. If this works i will be really excited.
</div>
<div class="announcements2" id="notif2">
Cover the white page.
</div>
</body>
Save the values used before you set these, and reset them when you "un-dock". Simply setting "docked" to show that you're un-docked is not enough.
This code is an example of how to do that from your staring point.
Here's how I saved it and got something like the behaviour you mention
var h = 0;
var notif;
var notif2;
var init;
var docked = false;
// holding space for reset values
var holdNotifyStyleTop;
var holdNotifyOffsetTop;
var holdNotif2StyleMarginTop;
function getSize() {
h = window.innerHeight;
notif = document.getElementById("notif");
notif2 = document.getElementById("notif2");
var fl = document.getElementById("floater");
init = notif.offsetTop;
notif.style.top = ""+h+"px";
var h2 = h/2;
fl.style.marginTop = ""+h2+"px";
notif.style.height = ""+h+"px";
var twoh = 3*h2;
notif2.style.top=""+h+"px";
notif2.style.height = ""+h+"px";
}
window.onscroll = function () {
if (!docked && (notif.offsetTop - document.body.scrollTop < 0)) {
console.log("--- DOCKING ---");
// save current values
holdNotifyStyleTop = notif.style.top;
holdNotifyOffsetTop = notif.offsetTop;
holdNotif2StyleMarginTop = notif2.style.marginTop;
notif.style.top = 0;
notif.style.position = 'fixed';
notif2.style.marginTop=""+h+"px";
docked = true;
} else if (docked && document.body.scrollTop <= init) {
console.log("--- Un-DOCKING ---");
notif.style.top = holdNotifyStyleTop;
notif.style.position = 'relative';
notif2.style.marginTop=holdNotif2StyleMarginTop;
notif.offsetTop = holdNotifyOffsetTop;
docked = false;
}
};

View zoom image when mouse over on thumbnail

This is for view zoom image when mouse over on thumbnail. IT'S WORKS !!!
1. Code for html (smarty)
<{html_image onmouseout="view_zoom(this, '');" onmouseover="view_zoom(this, this.src);" file=$img}>
2. Code for js :
function view_zoom(o, i)
{
if(i!=''&&i.indexOf('noimage.jpg') == -1)
{
var s = i.replace('small','big');
var aTag = o;
var leftpos = toppos = 0;
do {aTag = aTag.offsetParent; leftpos += aTag.offsetLeft; toppos += aTag.offsetTop;
} while(aTag.offsetParent != null);
var X = o.offsetLeft + leftpos + 100;
var Y = o.offsetTop + toppos - 20;
document.getElementById('big_zoom').style.left = X + 'px';
document.getElementById('big_zoom').style.top = Y + 'px';
document.getElementById('big_zoom').style.display = 'block';
document.getElementById('big_zoom').innerHTML='<img src="'+s+'" onload="if(this.width<200) {$(\'big_zoom\').style.display = \'none\');}else if(this.width>300){this.width=300;}$(\'big_zoom\').style.width=this.width+\'px\';"/>'
} else {
document.getElementById('big_zoom').style.display = 'none';
}
}
3. code for css :
.big_zoom {width:200px;z-index:1000;position:absolute;padding:5px; background:#FFFFFF;}
.big_zoom img{border:#AACCEE 1px solid;padding:5px;}
don't forget to add this line in html
<div class="big_zoom" id="big_zoom" style="display:none;"></div>
lol !!!

Categories

Resources