Why isn't the event fired when I load the document? - javascript

// I'm trying to create div elements using a FOR loop but the event is not fired, although I found a solution, I wanna know why the event isn't fired
// load event here is not fired
document.addEventListener('load', () => {
for (i = 0; i <= 32; i++) {
let gridSquare = document.createElement('div');
gridSquare.className = 'grid-square'
document.querySelector('.container').appendChild(gridSquare);
console.log(gridSquare,i)
}
});
// Random Text
<!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">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/style.css">
<title>Javascript Test run</title>
</head>
<body>
<header>
<h1 class="h1">Etch-A-Sketch</h1>
</header>
<main>
<--! Therefore DOM elements aren't created inside this div !-->
<div class="container"></div>
</main>
</div>
<script src="/main.js"></script>
</body>
</html>
// Random Text

Try with window.onload
window.onload = () => {
for (i = 0; i <= 32; i++) {
let gridSquare = document.createElement('div');
gridSquare.className = 'grid-square'
document.querySelector('.container').appendChild(gridSquare);
console.log(gridSquare,i)
}
}

Related

I am trying to use an user HTML input to change a javascript object value

I am trying to use HTML 'input' to change apiData.id value. I'm new to javascript and not sure if this is correct. Any suggestions would be greatly appreciated.
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
const newId = apiData.id;
function eventController(event) {
newId = event.target.value;
}
input.addEventListener('change', eventController, false);
<!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>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>
<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>
newId is const, so you cannot assign it with a new value after it has been declared.
But even if you could (and you can, by making it a variable), that would not affect apiData.id, as newId is assigned with the value of apiData.id, but they are not bound together.
You should just assign apiData.id directly with a new value:
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
// const newId = apiData.id;
function eventController(event) {
apiData.id = event.target.value;
}
input.addEventListener('change', eventController, false);
<!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>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>
<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>

can't select element with dom, after creating that element with other function - appendChild

How i'm supposed to select my element that have been created by function. First function is working well, but while i'm trying to select the element that been created in that function, it doesn't work
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function () {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
body.appendChild(c);
});
document.querySelector("p").addEventListener("click", function () {
console.log("Hi");
});
<!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>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="lop">s</div>
<div class="body"></div>
<script src="script.js"></script>
</body>
</html>
That's because you are attempting to attach a click event to your paragraph tag before its ever been added to the DOM.
You will need to move this new event listener inside of your onclick and after you append it to your .body div.
Example:
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function () {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
body.appendChild(c);
document.querySelector("p").addEventListener("click", function () {
console.log("Hi");
});
});
As requested, here is how you could just split some of this out to be its own methods for clarity. Feel free to use your own style as its just an example:
const onClickLop = (e) => {
const el = document.createElement("p");
const bodyDiv = document.querySelector(".body");
el.appendChild(document.createTextNode("lopas"));
bodyDiv.appendChild(el);
el.addEventListener("click", onClickLopas);
};
const onClickLopas = (e) => {
console.log("Hi");
});
document.querySelector(".lop").addEventListener("click", onClickLop);
Problem:
You create the p element at the moment when you click on .lop
You try to add the event listener at the page load. At this point there is no p tag at all.
Solution:
Add the event listener after you created the p tag.
You could also use the reference c instead of querySelector.
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function() {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
body.appendChild(c);
c.addEventListener("click", function() {
console.log("Hi");
});
});
<!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>
<div class="lop">s</div>
<div class="body"></div>
</body>
</html>
The code to add the event listener for the p element is executing before your code that creates it. Move the event handler into the first function so that it isn't triggered until the element is created and added to the document. However, that will mean that each time you click the first element, a new p will be created with its own handler (separate question/answer).
Also, by doing that you can consolidate some code.
let d = document.querySelector(".lop");
let body = document.querySelector(".body");
d.addEventListener("click", function () {
let c = document.createElement("p");
c.appendChild(document.createTextNode("lopas"));
c.addEventListener("click", function () {
console.log("Hi");
});
body.appendChild(c);
});
<!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>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="lop">s</div>
<div class="body"></div>
<script src="script.js"></script>
</body>
</html>

javascript addEventListener and click function not working for me on Anchor tag <a>

i hava also tried jquery but not worked for me i dont know why.
this is my javascript code
var cartLinks = document.getElementsByClassName('update-cart')
console.log(cartLinks)
for (var i = 0; i < cartLinks.length; i++) {
console.log('enterd in loop')
cartLinks[i].addEventListener("click", function () {
console.log('print...')
var productId = this.dataset.product
console.log(productId)
})
}
this is the tag where i want to use.
<i class="ion-bag"></i>
this is how i used script in my code.
<body>
some code
some scripts
<script src="{% static 'js/cart.js' %}"></script>
</body>
Hi your code is as follow
<!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>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha3841BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">
</head>
<body>
hello
text1
text1
text1
text1
<script src="cart.js"></script>
</body>
</html>
cart.js
var cartLinks = document.getElementsByClassName('update-cart')
console.log(cartLinks)
for (var i = 0; i < cartLinks.length; i++) {
console.log('enterd in loop')
cartLinks[i].addEventListener("click", function() {
console.log('print...')
var productId = this.dataset.product
console.log(productId)
})
}
add cart.js file at the end. Your javascript file load first then the anchor tag. That is only problem I have found...

Making options from 0 to 100 with javascript

I need to make section with options in it going from 0 to 100 when the page is open, in html is simple just type it all out :D, but i think i can do this in java script but i am not quite sure how.
Here is my html and a little bit of js code:
function options() {
var section = document.getElementById("section");
for(var i = 0;i < 100;i++){
section.innerHTML = "<option value="i">"+i+"</option>";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<section id="section" onload="options">
</section>
</body>
</html>
Here's How you can do it -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<select id="mySelect" onload="options()"></select>
</html>
<script type="text/javascript">
var selectElem = document.getElementById("mySelect");
for (var i = 0; i < 100; i++){
var element = document.createElement("option");
element.innerText = i + 1;
selectElem.append(element);
}
</script>
Here's the working example
<section> tag doesn't support onload.
You can check w3schools onload event and MDN: onload, the tags support onload are: <body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>
So you can move onload="options()" to <body> then escape the double quotes and use <select> instead of <section> as the comments mentioned.
function options() {
var section = document.getElementById("section");
for(var i = 0;i < 100;i++){
section.innerHTML += "<option value=\"i\">"+i+"</option>";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body onload="options()">
<select id="section">
</select>
</body>
</html>

Click on element and stopPropagation() for another one

I have two events: A button event and a container event. I want to apply stopPropagation() for container function, when I click on button. How to do this in vanilla js?
Now when I click on button #btn two functions will called. My goal is, when I click on button #btn, the code for #btn should only run. Click on div with id #container shall do it the same.
const btn = document.getElementById('btn');
btn.addEventListener('click', ()=> {
console.log('click on btn')
})
const container = document.getElementById('container');
container.addEventListener('click', ()=> {
console.log('click on container')
})
#container {
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<title>Welcome</title>
</head>
<body>
<div id="container">
<button id="btn">click</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
You can use Element.closest() to detect click outside or inside specific element
check this example
const btn = document.getElementById('btn');
btn.addEventListener('click', ()=> {
console.log('click on btn')
})
const container = document.getElementById('container');
container.addEventListener('click', (e)=> {
if(!e.target.closest('#btn')){
console.log('click on container')
}
})
#container {
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<title>Welcome</title>
</head>
<body>
<div id="container">
<button id="btn">click</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
Simply add event.stopPropagation in your btn click handler
btn.addEventListener('click', ()=> {
console.log('click on btn')
event.stopPropagation()
})

Categories

Resources