How to make newly cloned buttons work with an existing eventlistener? - javascript

On the press of the button 'leave' I want 10 new 'leave' buttons to be displayed on the screen. Each one of these buttons needs to display 10 new buttons on the screen when clicked.
But only the original 'leave' button displays 10 new buttons, the newly cloned ones don't.
Javascript code:
const container = document.querySelector('.container');
const leaveButton = document.querySelector('#leave');
leaveButton.addEventListener('click', () => {
for (let i = 0; i < 10; i++) {
const newButton = document.createElement('button');
newButton.innerHTML = leaveButton.innerHTML;
newButton.style.top = Math.random() * window.innerHeight + 'px';
newButton.style.left = Math.random() * window.innerWidth + 'px';
newButton.setAttribute("id", "leave");
container.appendChild(newButton);
}
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PressTheButton</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<button id="leave">Leave</button>
<h1>It's simple</h1>
<p>Just click the buttons</p>
</div>
<script src="script.js"></script>
</body>
</html>

Instead of adding the event listener to a fixed button you should work with delegated event listening. In the snippet below I added the click event to the parent container. Inside the event listener callback function I briefly check, wether the .textContent of the clicked element is equal to "Leave" and, if not, I return immediately without carrying out any action.
const container = document.querySelector('.container');
const leaveButton = document.querySelector('#leave');
container.addEventListener('click', ev => {
if (ev.target.textContent!=="Leave") return;
for (let i = 0; i < 10; i++) {
const newButton = document.createElement('button');
newButton.innerHTML = leaveButton.innerHTML;
newButton.style.top = Math.random() * window.innerHeight + 'px';
newButton.style.left = Math.random() * window.innerWidth + 'px';
newButton.setAttribute("id", "leave");
container.appendChild(newButton);
}
});
button {position:absolute}
<head>
<meta charset="UTF-8">
<title>PressTheButton</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<button id="leave">Leave</button>
<h1>It's simple</h1>
<p>Just click the buttons</p>
</div>

Related

i cant get the clicked elements child and change the div's background to that image

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF[![enter image description here][1]][1]-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Cubix Worlds Planner</title>
</head>
<body>
<div class="navbar">
<button class="btn">Reset</button>
</div>
<div class="blocks">
<button class="block"><img src="assets/blocks/items3.png"></button>
<button class="block"><img src="assets/blocks/items4.png"></button>
<button class="block"><img src="assets/blocks/items5.png"></button>
<button class="block"><img src="assets/blocks/items6.png"></button>
<button class="block"><img src="assets/blocks/items8.png"></button>
<button class="block"><img src="assets/blocks/items10.png"></button>
</div>
<div class="container">
</div>
<script src="main.js"></script>
</body>
</html>
main.js
const container = document.querySelector('.container');
const resetBtn = document.querySelector('.btn');
const { body } = document;
const blocklist = document.querySelector('.blocks');
const block = document.querySelector('.block');
let draw = false;
let blockimg = '';
function populate(size) {
document.querySelector('.block').addEventListener('click', e=>{
if (e.target.classList.contains('img')) {
blockimg = e.target.querySelector('img').getAttribute('src');
}
});
container.style.setProperty('--size', size);
for (let i = 0; i < size * size; i++) {
const div = document.createElement('div');
div.classList.add('pixel');
div.addEventListener('mouseover', function(){
if(!draw) return;
div.style.backgroundColor = blockimg;
});
div.addEventListener('mousedown', function(){
div.style.backgroundColor = blockimg;
});
container.appendChild(div);
}
}
window.addEventListener("mousedown", function(){
draw = true;
});
window.addEventListener("mouseup", function(){
draw = false;
});
function reset() {
container.innerHTML = '';
populate(100);
}
resetBtn.addEventListener('click', reset);
populate(100);
let zoomActivate = false;
window.addEventListener('keydown', (e) => {
if(e.key === 'z') {
zoomActivate = !zoomActivate;
}
});
window.addEventListener("mousemove", (e) => {
const { clientX: x, clientY: y } = e;
if(zoomActivate) {
body.style.transform = 'scale(2)';
body.style.transformOrigin = `${x}px ${y}px`;
} else {
body.style.transform = 'none';
}
});
Over the past few days, I have been attempting to create a website for pixel art. However, instead of using colors, I have opted to use blocks that can be placed on a canvas. Unfortunately, I have encountered an issue with the code I have written, as it does not allow me to select the specific block that I wish to place on the canvas. As a result, I am unable to properly generate the desired pixel art.
website preview
https://i.stack.imgur.com/ydp8M.png

Trying to figure out why balloon pop game is not resetting clickCount

I have followed along with video from video number 76 of the Udemy "last Intro to Programming Course". I have moved code that was included all in one function to another function called "draw" I have reviewed the video multiple times and I cannot see any difference between my code and the video. The goal of the code is to reset the clickCount back to zero. Here is the code. Help would be greatly appreciated everything is working except resetting of the balloon size and clickCount with each timeout:
let startButton = document.getElementById('start-button')
let inflateButton = document.getElementById('inflate-button')
let clickCount = 0
let height = 120
let width = 100
let inflationRate = 20
let maxsize = 300
let popCount = 0
function startGame() {
startButton.setAttribute("disabled", "true")
inflateButton.removeAttribute("disabled")
setTimeout(() => {
console.log("it's been 3 seconds")
inflateButton.setAttribute("disabled", "true")
startButton.removeAttribute("disabled")
clickCount = 0
height = 120
width = 100
draw()
}, 3000)
}
function inflate() {
clickCount++
height += inflationRate
width += inflationRate
if (height >= maxsize) {
console.log("pop the balloon")
popCount++
height = 0
width = 0
}
draw()
}
function draw() {
let balloonElement = document.getElementById("balloon")
let clickCountElem = document.getElementById("click-count")
let popCountElem = document.getElementById('pop-count')
balloonElement.style.height = height + "px"
balloonElement.style.width = width + "px"
clickCountElem.innerText = clickCount.toString()
popCountElem.innerText = popCount.toString()
}
<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>Balloon Pop</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<button id="start-button" onclick="startGame()" >START GAME</button>
</div>
<button id="inflate-button" onclick="inflate()" disabled="true">Inflate <span id="click-count"> </span></button>
<div>
<span>Balloons Popped</span>
<span id="pop-count"></span>
</div>
<div id="balloon" class="balloon" ></div>
<script src="main.js"></script>
</body>
</html>
I figured this out by looking at the source tab in dev tools. For whatever reason all of the lines weren't being saved or loaded to Chrome from VSCode. What I did was copy all the code from VSCode and pasted it into Notepad, saved and then refreshed. All is working fine now.

Why is require('fs') causing my js variables to not show in html?

I'm trying to make an electron app that increments and reduces a number and updates that number to a local .txt file.
I have the numbers displaying and counting up/down but as soon as I introduce the fs node it reverts to the placeholder text of "ScoreA"
var fs = require('fs');
//Score A initialise
var scoreAOriginal = 0;
var dx = scoreAOriginal;
//Score A button functions
function incA(num){
dx = dx + num;
}
function decA(num){
if (dx >= 1){
dx = dx - num;
}
}
//Score B initialise
var scoreBOriginal = 0;
var dy = scoreBOriginal;
//Score B button functions
function incB(num){
dy = dy + num;
}
function decB(num){
dy = dy - num;
}
// Refresher and value assignment to div classes in index.html
setInterval(function(){ document.getElementById("scoreA").innerHTML = dx; document.getElementById("scoreB").innerHTML = dy; }, 100);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Peppy - by Doug</title>
<script src="./main.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<h1>Peppy</h1>
<div class="scoreConsoles">
<div>
<button class="button button5" onclick="incA(1)">+</button>
<div id="scoreA">scoreA</div>
<button class="button button5" onclick="decA(1)">-</button>
</div>
<div>
<button class="button button5" onclick="incB(1)">+</button>
<div id="scoreB">scoreB</div>
<button class="button button5" onclick="decB(1)">-</button>
</div>
</div>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
How did you create the window? You know you need to enable node integration:
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});

How can i call setInterval more than one time?

So, i want to call setInterval with a button multiple times, but when i press the button a second time nothing happens. I have searched for other similar questions but they are in jQuery and dont worked for me.
Edit: What i wan't to do is to repeat the animation by clicking the button.
var element, add, intervalo;
add = 0;
function start(){
intervalo = setInterval(interval, 50);
}
function interval() {
add = add + 25;
element = document.getElementById('teste');
element.style.left = add;
if (add > 300) {
clearInterval(intervalo);
intervalo = null;
element.style.left = 0;
}
}
#teste {
position: absolute;
}
<html>
<head>
<script src="js/main.js"></script>
<link rel="stylesheet" src="text/css" href="css/estilo.css">
</head>
<body>
<h1 id="teste">Ola</h1>
<button onclick="start()">Start</button>
</body>
</html>
You are not resetting your add variable so when the interval is triggered a second time it will go right to the clearInterval section.
var element, add, intervalo, btn, element;
add = 0;
btn = document.getElementById('btn');
element = document.getElementById('teste');
function start() {
btn.disabled = true;
intervalo = setInterval(interval, 50);
}
function interval() {
add = add + 25;
element.style.left = add + 'px';
if (add > 300) {
clearInterval(intervalo);
intervalo = null;
element.style.left = 0;
btn.disabled = false;
add = 0;
}
}
#teste {
position: absolute;
left: 0;
top: 0;
}
<html>
<head>
<script src="js/main.js"></script>
<link rel="stylesheet" src="text/css" href="css/estilo.css">
</head>
<body>
<h1 id="teste">Ola</h1>
<button id="btn" onclick="start()">Start</button>
</body>
</html>

Create Element with id and styles using pure JS

I build a small function appending an element with an id and styles.
And know my question why does this code not work?
window.addEventListener("load",function(e){
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.style = function (){
height = "200px";
width = "400px";
position = "fixed";
top = "50%";
left = "50%";
marginLeft = -1*(this.width / 2);
marginTop = -1*(this.height / 2);
};
body.appendChild(inButton);
}, false);
I use the following html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="description"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<script type="text/javascript" src="js/vendor/modernizr-.8.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="js/plugins.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
The Js Code is inside the main.js.
I checked the path again and again, but the path is totally correct.
You are not setting style property correctly. Rest of code is correct.
Here's an example
window.addEventListener("load", function(e) {
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.innerHTML = "Yahooooooooooooooo"; //For example
inButton.style.height = "200px";
inButton.style.width = "400px";
inButton.style.position = "fixed";
inButton.style.top = "50%";
inButton.style.left = "50%";
inButton.style.marginLeft = -1 * (this.width / 2);
inButton.style.marginTop = -1 * (this.height / 2);
body.appendChild(inButton);
}, false);

Categories