Cannot delete buttons using js - javascript

I can't delete two <button> tags using javascript. When you enter the wrong pin, I want the buttons to delete themselves but somehow it's not working.
var radar = document.getElementsByTagName("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin) {
document.write("Podany pin: " + pin_request);
alert("Podano właściwy pin.");
} else {
document.write("odmowa dostępu.");
radar.parentNode.removeChild(radar);
}
<html>
<head>
<meta charset="UTF-8">
<style>
html {
text-align: center;
padding: 7em;
display: block;
}
button {
margin: 1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniądze</button>
<button>zainwestuj w nieruchomości</button>
<script src="do visual studio code.js"></script>
</body>
</html>
Also sorry for half-English code.

You can use querySelectorAll to get elements and in loop remove them.
var radar = document.querySelectorAll("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
radar.forEach(el=>{
el.remove();
})
}
<html>
<head>
<meta charset="UTF-8">
<style>
html{text-align:center; padding:7em; display:block;}
button{
margin:1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniądze</button>
<button>zainwestuj w nieruchomości</button>
<script src="do visual studio code.js"></script>
</body>

getElementyByTagName() returns an array of elements, but removeChild() only takes one element as an argument. If you use a loop it should work:
var parent = radar[0].parentNode
for(var i = 0; i < radar.length; i++) {
parent.removeChild(radar[i])
}

<!DOCTYPE HTML5>
<html>
<head>
<meta charset="UTF-8">
<style>
html{text-align:center; padding:7em; display:block;}
button{
margin:1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniądze</button>
<button>zainwestuj w nieruchomości</button>
<script>
var radar = document.querySelectorAll("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
radar.forEach(ele =>{
ele.remove();
})
}
</script>
</body>
</html>

This should work
var radar = document.getElementsByTagName("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
var elem = document.getElementById('btn1');
elem.parentNode.removeChild(elem);
var elem2 = document.getElementById('btn2');
elem2.parentNode.removeChild(elem2);
}
<button id = 'btn1'>dodaj pieniądze</button>
<button id = 'btn2'>zainwestuj w nieruchomości</button>

Related

How to make a custom confirmation dialog for critical actions

I was creating a dialog to confirm action by user.
We can achieve that by confirm() dialog like this:
function btnChangeBodyColorFunc() {
let text = "You are going to change body color.Are you sure";
if (confirm(text) == true) {
document.body.style.backgroundColor = "red";
console.log("You changed!");
} else {
document.body.style.backgroundColor = "";
console.log("You canceled!");
}
}
<button onclick="btnChangeBodyColorFunc()">Change body color to red</button>
But can it be sort of custom like this:
let iConfirmToGoAhead = ""
let confirmDialog = document.querySelector(".confirmDialog");
function btnChangeBodyColorFunc() {
confirmDialog.style.display = "flex";
if (iConfirmToGoAhead === "true") {
document.body.style.backgroundColor = "red";
console.log("You changed!");
iConfirmToGoAhead = ""
} else if (iConfirmToGoAhead === "false") {
document.body.style.backgroundColor = "";
console.log("You canceled!");
iConfirmToGoAhead = ""
}
}
let confirmDialogBtn = document.querySelectorAll(".confirmDialogContent button");
for (let i = 0; i < confirmDialogBtn.length; i++) {
confirmDialogBtn[i].addEventListener('click', confirmDialogBtnFunc)
}
function confirmDialogBtnFunc() {
confirmDialog.style.display = "none";
iConfirmToGoAhead = this.dataset.confirmationValue;
}
.confirmDialog {
position: fixed;
display: none;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.7);
height: 100vh;
width: 100vw;
}
.confirmDialogContent {
margin: auto;
}
<button onclick="btnChangeBodyColorFunc()">Change body color to red</button>
<div class="confirmDialog">
<div class="confirmDialogContent">
You are going to change body color.Are you sure
<button data-confirmation-value="true">Yes sure</button>
<button data-confirmation-value="false">No don't change</button>
</div>
</div>
But this way it don't wait for iConfirmToGoAhead value to be confirmed and execute the function.
Know this is how JS works that execute the codes which comes first. I tried use of async and await but that also don't work and throw error(might not applied it right).
Can do required functionality by adding conditions to second function but thought a common way for all critical actions through 1 dialog and change according to it.
Is it possible to have a custom confirmation dialog like this or have to use conditions in 2nd function. Any ideas are most welcome
Thanks for help in advance
As you mentioned in this line, any button click action inside the class confirmDialogContent, should trigger an event & call this function confirmDialogBtnFunc. But you have written all functionality inside the function btnChangeBodyColorFunc.
This function will call only when you click the button Change body color to red. If you make any click event inside the confirmation popup, it will call the confirmDialogBtnFunc function as you mentioned inside the for loop
let confirmDialogBtn = document.querySelectorAll(".confirmDialogContent button");
for (let i = 0; i < confirmDialogBtn.length; i++) {
confirmDialogBtn[i].addEventListener('click', confirmDialogBtnFunc)
}
I have rewritten the code, Please look into it.
I hope that would be useful for you :)
let iConfirmToGoAhead = ""
let confirmDialog = document.querySelector(".confirmDialog");
function btnChangeBodyColorFunc() {
confirmDialog.style.display = "flex";
}
let confirmDialogBtn = document.querySelectorAll(".confirmDialogContent button");
for (let i = 0; i < confirmDialogBtn.length; i++) {
confirmDialogBtn[i].addEventListener('click', confirmDialogBtnFunc)
}
function confirmDialogBtnFunc() {
iConfirmToGoAhead = this.dataset.confirmationValue;
confirmDialog.style.display = "flex";
if (iConfirmToGoAhead === "true") {
document.body.style.backgroundColor = "red";
console.log("You changed!");
iConfirmToGoAhead = ""
} else if (iConfirmToGoAhead === "false") {
document.body.style.backgroundColor = "";
console.log("You canceled!");
iConfirmToGoAhead = ""
}
confirmDialog.style.display = "none";
}
.confirmDialog {
position: fixed;
display: none;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.7);
height: 100vh;
width: 100vw;
}
.confirmDialogContent {
margin: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="btnChangeBodyColorFunc()">Change body color to red</button>
<div class="confirmDialog">
<div class="confirmDialogContent">
You are going to change body color.Are you sure
<button data-confirmation-value="true">Yes sure</button>
<button data-confirmation-value="false">No don't change</button>
</div>
</div>
</body>
</html>

Auto-Play feature not executing in JS

I have somewhat of a baseball game, obviously there are not bases or hits. Its all stikes, balls and outs. The buttons work and the functionality of the inning (top and bottom as well as count) are working. I want this to ideally randomly throw a pitch on its own every few seconds. Basically to randomly "click" the ball or strike button. I am trying to use the setTimeout function with no success. Any help?
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="bullpen.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bullpen</title>
</head>
</html>
<body>
<button id=buttons onclick="playBall()">Auto-Play</button>
<h2>Inning: <span id=inningHalf></span> <span id=inningNum></span></h2>
<div id=buttons>
<button onclick="throwBall(), newInning()">Ball</button>
<button onclick="throwStrike(), newInning()">Strike</button>
</div>
<h2>Count: <span id=ball>0</span> - <span id=strike>0</span></h2>
<h2>Outs: <span id=out>0</span></h2>
<h2>----------------</h2>
<h2>Walks: <span id=walks>0</span></h2>
<h2>Strikeouts: <span id=strikeout>0</span></h2>
<script src="bullpen.js"></script>
</body>
</html>
JS:
var ball = 0;
var strike = 0;
var out = 0;
var walks = 0;
var strikeout = 0;
//---------------------------------
var outPerInning = 0;
var inning = 1;
//---------------------------------
document.getElementById('inningNum').innerHTML = inning;
document.getElementById('inningHalf').innerHTML = '▲';
function throwBall(){
ball++;
document.getElementById('ball').innerHTML = ball;
if (ball == 4){
ball = 0;
strike = 0;
walks++;
document.getElementById('walks').innerHTML = walks;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function throwStrike(){
strike++;
document.getElementById('strike').innerHTML = strike;
if(strike == 3){
ball = 0;
strike = 0;
strikeout++;
out++;
outPerInning++;
document.getElementById('strikeout').innerHTML = strikeout;
document.getElementById('out').innerHTML = out;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function newInning(){
if(out == 3){
ball=0;
strike=0;
out=0;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
document.getElementById('out').innerHTML = 0;
}
if(outPerInning == 3){
document.getElementById('inningHalf').innerHTML = '▼';
}
if(outPerInning == 6){
inning++;
document.getElementById('inningHalf').innerHTML = '▲';
outPerInning = 0;
document.getElementById('inningNum').innerHTML = inning;
}
};
function playBall(){
var play = Math.random;
if(play >= 0.4){
throwStrike();
newInning();
}
else{
throwBall();
newInning();
}
setTimeout(playBall, 5000);
};
CSS if needed:
h2{
margin-left: 50px;
font-size: 50px;
}
button{
font-size: 45px;
}
#buttons{
width: 227px;
margin-left:50px;
margin-top: 20px;
}
Perhaps this is the problem:
function playBall(){
var play = math.random;
if(play >= 0.4){
throwStrike;
newInning();
}
else{
throwBall;
newInning();
}
setTimeout(playBall, 5000);
};
Should be
function playBall(){
var play = Math.random();
if(play >= 0.4){
throwStrike(); //call the function
newInning();
}
else{
throwBall(); //call the function
newInning();
}
setTimeout(playBall, 5000);
};
You were not calling these functions!
Here is a working fiddle: https://jsfiddle.net/av6vsp7g/

Why IIFE can fix "cannot set property 'onclick' of null"

I have a block of code as the following
<body id="main">
<h1>Matching Game</h1>
<p>Click on the extra smile face on the left</p>
<div id="left_side"></div>
<div id="right_side"></div>
<script>
var theLeftSide = document.getElementById("left_side");
var theRightSide = document.getElementById("right_side");
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
quan+=5;
dele();
generateFace();
}
</script>
</body>
This line theLeftSide.lastChild.onclickwill throw an error, saying that "cannot set property 'onclick' of null", because at the time javascript engine scans through it, it hasn't has any child yet. This problem can be solved by putting this code inside $(document).ready, I know.
However, I also tried IIFE, which means that wrapping all those code inside
(function(){
var theLeftSide = document.getElementById("left_side");
var theRightSide = document.getElementById("right_side");
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
quan+=5;
dele();
generateFace();
}
})()
and also see that the problem is fixed, but cannot figure out why. Any one can explain me ?
Here's the full original code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>part4</title>
<style>
div{
position:absolute;
}
#left_side{
width:500px; height: 500px; border-right:#000 thin inset;
float: left;
}
#right_side{
width:500px; height: 500px;
float:left; left:500px;
}
img{
position: absolute;
}
body{
margin:0px;
}
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
</head>
<body onload="generateFace()" id="main">
<h1>Matching Game</h1>
<p>Click on the extra smile face on the left</p>
<div id="left_side"></div>
<div id="right_side"></div>
<script>
var theLeftSide = document.getElementById("left_side");
var theRightSide = document.getElementById("right_side");
var e = event;
var theBody= document.getElementById("main");
var post_left =0;
var post_top=0;
var quan = 4;
function generateFace(){
var i =0;
for(i=0; i<= quan; i++){
var img = document.createElement("img");
img.src="smile.png"; post_top=getRandom(); post_left=getRandom();
img.style.top = post_top + "px";
img.style.left = post_left +"px";
theRightSide.appendChild(img);
var clone = img.cloneNode(true);
theLeftSide.appendChild(clone);
}
//var clone = theRightSide.cloneNode(true);
//theLeftSide.appendChild(clone);
var extra = document.createElement("img");
extra.src="smile.png"; post_top=getRandom(); post_left=getRandom();
extra.style.top = post_top + "px";
extra.style.left = post_left +"px";
theLeftSide.appendChild(extra);
};
function getRandom(){
var i = Math.random() * 400 +1;
return Math.floor(i);
};
function dele(){
while(theLeftSide.firstChild != null){
theLeftSide.removeChild(theLeftSide.firstChild);
}
while(theRightSide.firstChild != null){
theRightSide.removeChild(theRightSide.firstChild);
}
};
theBody.onclick = function gameOver() {
alert("Game Over!");
dele();
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
function nextLevel(event){
event.stopPropagation();
quan+=5;
delse();
generateFace();
}
</script>
</body>
</html>
and with IIFE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>part4</title>
<style>
div{
position:absolute;
}
#left_side{
width:500px; height: 500px; border-right:#000 thin inset;
float: left;
}
#right_side{
width:500px; height: 500px;
float:left; left:500px;
}
img{
position: absolute;
}
body{
margin:0px;
}
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
</head>
<body id="main">
<h1>Matching Game</h1>
<p>Click on the extra smile face on the left</p>
<div id="left_side"></div>
<div id="right_side"></div>
<script>
(function(){
var theLeftSide = document.getElementById("left_side");
var theRightSide = document.getElementById("right_side");
var e = event;
var theBody= document.getElementById("main");
var post_left =0;
var post_top=0;
var quan = 4;
generateFace();
function generateFace(){
var i =0;
for(i=0; i<= quan; i++){
var img = document.createElement("img");
img.src="smile.png"; post_top=getRandom(); post_left=getRandom();
img.style.top = post_top + "px";
img.style.left = post_left +"px";
theRightSide.appendChild(img);
var clone = img.cloneNode(true);
theLeftSide.appendChild(clone);
}
//var clone = theRightSide.cloneNode(true);
//theLeftSide.appendChild(clone);
var extra = document.createElement("img");
extra.src="smile.png"; post_top=getRandom(); post_left=getRandom();
extra.style.top = post_top + "px";
extra.style.left = post_left +"px";
theLeftSide.appendChild(extra);
};
function getRandom(){
var i = Math.random() * 400 +1;
return Math.floor(i);
};
function dele(){
while(theLeftSide.firstChild != null){
theLeftSide.removeChild(theLeftSide.firstChild);
}
while(theRightSide.firstChild != null){
theRightSide.removeChild(theRightSide.firstChild);
}
};
theBody.onclick = function gameOver() {
alert("Game Over!");
dele();
//theBody.onclick = undefined;
//theLeftSide.lastChild.onclick = undefined;
};
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
quan+=5;
dele();
generateFace();
}
})();
</script>
</body>
</html>
In the original piece of code, generateFace() is called on page load. In the second piece of code, generateFace() is called directly. There is no relation with the IIFE. Please forget it! :-P Here is a simplified version of what you are doing in each case (open your browser console before running the snippets):
Original code (throws a TypeError)
console.log('attempting to initialize onclick');
document.getElementById('clickable').onclick = function () {
alert(this.id);
};
console.log('onclick initialized successfully');
function gendiv () {
console.log('gendiv was called');
document.body.innerHTML = '<div id="clickable">click me</div>';
}
<body onload="gendiv()"></body>
Modified code
gendiv();
console.log('trying to initialize onclick');
document.getElementById('clickable').onclick = function () {
alert(this.id);
};
console.log('onclick initialized successfully');
function gendiv () {
console.log('gendiv was called');
document.body.innerHTML = '<div id="clickable">click me</div>';
}
<body></body>

Some problems in IE11

The problem is that I have created a dynamic navigation...
You click on a a-tag which has a function that displays some buttons.
I have assigned the function to the a-tag with an addEventListener.
It works in all the browsers, but IE...
When I click the tag, buttons are not becoming visible. And no error appears.
P.S.: I'm spanish btw, I'm sorry about my english :3
/* Javascript */
window.onload = function() {
var boton_menu = document.getElementById("boton_menu");
/* Compatibilidad con navegadores web */
if(boton_menu.addEventListener){
boton_menu.addEventListener("click", menu_usuario, false);
} else {
if(boton_menu.attachEvent){
boton_menu.attachEvent("onclick", menu_usuario);
}
}
}
/* Despliega el menú del usuario*/
function menu_usuario() {
var boton_menu = document.getElementById("boton_menu");
var perfil = document.getElementById("perfil");
var ajustes = document.getElementById("ajustes");
var desconectar = document.getElementById("desconectar");
if(boton_menu.className == ""){
boton_menu.className = "active";
perfil.className = "active";
ajustes.className = "active";
desconectar.className = "active";
} else {
boton_menu.className = "";
perfil.className = "";
ajustes.className = "";
desconectar.className = "";
}
}
This works in IE:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="">
<meta charset="utf-8">
<meta name="author" content="Antonio Bueno">
<title>Button Problems</title>
<style>
a {background-color: red; color: #FFF; padding: 10px;}
a.active {background-color: blue;}
</style>
<script>
window.onload = function(){
var some_button = document.getElementById("some_button");
if(some_button.addEventListener){
some_button.addEventListener("click", DisplayButton, false);
} else {
if(some_button.attachEvent){
some_button.attachEvent("onclick", DisplayButton);
}
}
}
function DisplayButton(){
var some_button = document.getElementById("some_button");
var another_button = document.getElementById("another_button");
if(some_button.className == ""){
some_button.className = "active";
another_button.style.display = "none";
} else {
some_button.className = "";
another_button.style.display = "inline-block";
}
}
</script>
</head>
<body>
<a id="some_button" class="">Click on me</a>
<input id="another_button" type="submit" value="example" />
</body>
</html>

JavaScript/HTML div creation error

I am trying to make a basic sensor pad for HTML (JavaScript), which creates 500 small divs which then turn red on mouse hover. However, when I tried it, nothing was created
example.html
<!DOCTYPE html>
<html>
<head>
<title>SensorPad Test</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script type="text/javascript" src="SensorPad.js">
window.onload = createSensor;
</script>
</head>
</html>
styles.css
.sPad{
width: 0.4px;
height: 0.4px;
background-color: #EEE;
border: 0.1px solid #000;
}
.uPad{
background-color: #F00;
}
SensorPad.js
var sPos;
var count = 1;
function createSensor(){
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + count.toString();
pad.onmousehover = function(){sPos = parseInt(pad.id); clearPads(); pad.className = 'uPad';};
count++;
}
}
function clearPads(){
for(var i = 1; i <= count; ++i){
var n = 'pad' + i.toString();
var p = document.getElementById(n);
p.className = 'sPad';
}
}
You're missing
document.body.appendChild(pad);
First the code will not run because of the way you added the JavaScript
<script type="text/javascript" src="SensorPad.js">
window.onload = createSensor;
</script>
you can not have code inside and a src
<script type="text/javascript" src="SensorPad.js"></src>
<script type="text/javascript"
window.onload = createSensor;
</script>
First, you need to use separate script tags - one for the external reference and another for the onload.
As for the divs, you're creating them but you're not adding them to the DOM.
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + count.toString();
pad.onmousehover = function(){sPos = parseInt(pad.id); clearPads(); pad.className = 'uPad';};
document.body.appendChild(pad)
count++;
}
EDIT: Addressing Teemu's concern you might simply want to use CSS for that hover instead so:
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + i.toString();
document.body.appendChild(pad)
}
css
.sPad{
width: 0.4px;
height: 0.4px;
background-color: #EEE;
border: 0.1px solid #000;
}
.sPad:hover{
background-color: #F00;
}

Categories

Resources