Ways to wait for elements to load when adding eventlisteners - javascript

I'm playing around with parcel before I used liveserver in vscode and I rarely ran into this problem. I'm trying to add a eventlistener to a inputform. DOM isn't finding the element no matter what I do. I've tried to put a if statement checking if the element exist before putting a listener but it doesn't change anything. I never had this problem using liveserver, do i have to write a asynchronous function and wait for the page to load? I tried putting defer inside the script tag aswell. Is parcel slower than liveserver somehow?
const input1 = document.getElementById("input1");
if(input1)
{
console.log("The input exists");
input1.addEventListener('click', () =>{
console.log("heey");
});
}
<!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="./assets/scss/main.scss">
</head>
<body>
<form>
<div class="form-group">
<label for="inputlg">input</label>
<input class="form-control input-lg" id="inputlg" type="text" id="input1">
<label for="inputlg">output</label>
<input class="form-control input-lg" id="inputlg" type="text">
</div>
</form>
<script type="module" src="./assets/js/main.js" ></script>
</body>
</html>

Your input has two ids. That's invalid, and getElementById doesn't see the second one.
const input1 = document.getElementById('input1');
console.log(input1); // null
const inputlg = document.getElementById('inputlg');
console.log(inputlg); // input#inputlg.form-control.input-lg
<input class="form-control input-lg" id="inputlg" type="text" id="input1">

There are a few ways.
(best) document.addEventListener('DOMContentLoaded', () => { // code here })
document.onreadystatechange = () => { if (document.readystate == "complete") { // code here } }
Also, it is a requirement that there is only 1 element assigned to each ID. In your code, you have 2 elements with ID "inputlg", which is not allowed. Get rid of those and it should work. You also have an element which you are trying to have 2 IDs on, which also does not work.
The code above is just to make sure that the document is fully loaded, and prevents errors.

Related

Im new with call api , can someone help me with this . Call Api link shortener with javascript

So I have a mission is call api to this website : https://shrtco.de/ and using link shortener like them. But I don't know how to call it . Can someone explain how to call this or maybe help me , thank you guys so much
This is my HTML code :
<!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>
<p>Enter a link</p>
<input type="text">
<button>Enter</button> <br>
<p>Short domain</p>
<input type="radio" id="domain1" name="fav_language" value="domain1">
<label for="html">shrtco.de</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">9qr.de</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">shiny.link</label>
<p>Link generated</p>
ZZZZZ
</div>
<script src="getAPI.js"></script>
</body>
</html>
Following the example from the interface documentation, I have programmed a minimal illustrative example here.
<!DOCTYPE html>
<html>
<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>shortcode example</title>
</head>
<body>
<input type="text" name="url" id="url" value="" required>
<button id="submit" type="submit">shorten</button>
<p id="result"></p>
<script>
const button = document.querySelector('button');
const input = document.querySelector('input');
const result = document.getElementById('result');
const shorten = (event) => {
let value = input.value.trim();
while (result.firstChild) {
result.removeChild(result.firstChild);
}
if (!value.length) {
throw new Error('well! you have to type in something!');
}
let promise = fetch('https://api.shrtco.de/v2/shorten?url=' + value);
promise.then(response => {
if (response.status !== 201) {
console.log('Looks like there was a problem: ' + response.status);
return;
}
response.json().then(data => {
let link = document.createTextNode(data.result.full_short_link);
result.appendChild(link);
}).catch(error => {
console.log(error.message);
})
});
}
button.addEventListener('click', shorten, false);
</script>
</body>
</html>
What is happening in this example?
First there are three elements - an input element for typing in the url to shorten, a button element for submitting the data and a paragraph for displaying the results of the api call.
The submit button gets an javascript event listener, that handles click events. Everytime you click on that button, the input element will be checked, if something was typed in. If the value of the input element has a length, it will be send to the shortening service. For that reason we produce a promise with the javascript fetch api.
The call with the fetch api returns a javascript promise, which we check for the response status code. The api returns a 201 "Created" status code, that says everything is alright. The api needs a little time for the response, but then we can decode the json response and print out the shortened link in the result paragraph.
What you should do
Try to understand the given example. Please read the interface documentation to get informations about what could be returned in a success case and whats happening when the request fails? The javascript fetch api is elemental for that.
Try to transfer the given example to your application. If you encounter problems, explain these problems in detail and ask for a solution.

How do I let onClick() read from my javascript file?

I have two files index.html and index.js. When I fill the text fields in the form and click the button, it should redirect to index.js. How do I achieve that?
index.html
<!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>
<h1 id="head">Hello</h1>
<input type="email" id="email"></input>
<br><br>
<input type="password" id="pass"></input>
<br><br>
<button>Click</button>
<script src="index.js"></script>
</body>
</html>
index.js
if (document.getElementById("email").nodeValue==document.getElementById("pass").nodeValue){
alert("You are allowed");
}
EDIT: I can do this simply by creating the function inside the <script> tag itself and then calling the function inside onClick in the <button> tag. But instead, I want the onClick to call my index.js script which will perform the backend stuff
declare this function in index.js
function handleClick() {
if (
document.getElementById('email').nodeValue ===
document.getElementById('pass').nodeValue
) {
alert('You are allowed');
}
}
call it on button click
<button onclick="handleClick()">Click</button>
you should link the html file to the javascript file using
<script type="text/javascript" src="(your file location)"></script>
then add event listeners to listen to the button click using
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("button-id").addEventListener('click', yourFunction)
});
function yourFunction(){
//your code here
}
also add an id to the button so you can add the event listener to it
<button id="button-id">Click</button>
You need to use EventListener to bind button click event to a function.
document.getElementsByTagName('button')[0].addEventListener('click',function(){
if (document.getElementById("email").value==document.getElementById("pass").value){
alert("You are allowed");
}
});
<!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>
<h1 id="head">Hello</h1>
<input type="email" id="email"></input>
<br><br>
<input type="password" id="pass"></input>
<br><br>
<button>Click</button>
</body>
</html>
you should add the js file in your index.html
<script type="text/javascript" src="index.js"></script>
then you should add onclick event on your button
<button onclick="myFunction()">Click</button>
then in index.js you should add the function
function myFunction(){
//your logic goes here
}
Always call your script inside js only. It is bad practice to call scripts in the html structure. I gave you an example of calling script logic and accessing a component using querySelector().
var form_button = document.querySelector('.thisisbutton');
var email_input = document.querySelector("#email");
var pass_input = document.querySelector("#pass");
form_button.onclick = function() {
if (email_input.value == pass_input.value){
alert("You are allowed");
}
}
<body>
<h1 id="head">Hello</h1>
<input type="email" id="email">
<br><br>
<input type="password" id="pass">
<br><br>
<button class="thisisbutton">Click</button>
</body>

TypeError: Cannot read property of null [while calling external(defer)/internal JSFile]

The Html/JS(vanilla) script below ,gives the following error [when used with both an internal script aswell as an external JS file (using the "defer" keyword)] -
How could this error be resolved?
Chrome
Uncaught TypeError: Cannot read property 'onclick' of null
Firefox
TypeError: document.getElementById(...) is null
//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).
document.getElementById("change1").onclick(function(){
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change1 btn pressed");
}
)
document.querySelector("change2").addeventlistener("click",()=>{
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
},false
)
<!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">
<title>Event2</title>
<script src= "testJS_event2.js" defer ></script>
</head>
<body>
<div>
<p id="tx1">tx1 <--- this element is null </p>
<h1 id="tx2">tx2 <--- this element is also null </h1><br>
<button id = "change1">Change1</button>
<button id = "change2">Change2</button>
</div>
</body>
</html>
You need to assign function to the onclick event attribute of the element
For querySelector you need to access the element with a # as you are accessing the element with its id
There was a typo for addEventListener
<!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">
<title>Event2</title>
<script defer="defer">
window.onload = function() {
//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).
document.getElementById("change1").onclick = function() {
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change2 btn pressed");
};
document.querySelector("#change2").addEventListener("click", () => {
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
}, false);
}
</script>
</head>
<body>
<div>
<p id="tx1">tx1
<!--- this element is null-->
</p>
<h1 id="tx2">tx2
<!--- this element is also null -->
</h1>
<br>
<button id="change1">Change1</button>
<button id="change2">Change2</button>
</div>
</body>
</html>
Though defer is used and document is parsed, the defer script will fire before DOMContentLoaded, hence the error.
This Boolean attribute is set to indicate to a browser that the script
is meant to be executed after the document has been parsed, but before
firing DOMContentLoaded.
Scripts with the defer attribute will prevent the DOMContentLoaded
event from firing until the script has loaded and finished evaluating.
Your problem is that the Javascript is executed before you page is fully load, so it can find your elements.
Use window.onload() and it will be good !
Or you can put your <script src= "testJS_event2.js" defer ></script> at the end of your body (better solution for loading time)
You have typo in your code, addEventListener not addeventlistener.
getElementById returns HTMLElement or undefined. HTMLElement does not have onclick property, You need to bind a click event listener to it.
Lastly, you can only query the DOM once it is fully loaded. You JS execute before the code DOM is loaded. That is why the DOM elements your are querying are null/undefined.
You can also bind the onlick event in your butto directly. Here is a working sample code.
<!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">
<title>Event2</title>
<script src="testJS_event2.js"></script>
</head>
<body>
<div>
<p id="tx1">tx1 <--- this element is null </p>
<h1 id="tx2">tx2 <--- this element is also null </h1> <br>
<button id="change1">Change1</button>
<button id="change2">Change2</button>
<button onclick="change3()">Change3</button>
</div>
</body>
</html>
window.onload = function() {
document.getElementById("change1").addEventListener("click", function() {
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change1 btn pressed");
});
document.querySelector("#change2").addEventListener("click", function() {
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
});
};
function change3() {
console.log("Change 3 clicked .......");
}

Cannot set property innerHTML error

I am trying to automate the process of opening an external site from a button of an internal site that I created, but I can not reference the document I created, follow the code below, tried several times and could not, any help is valid, thank you so much.
<!DOCTYPE html>
<head>
<title>Principal</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="\\fswcorp\ceic\ssoa\gaacc\System\JQuery\jquery-3.2.1.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryMask\dist\jquery.mask.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryUI\jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#dateBegin").mask('00/00/0000');
$("#dateEnd").mask('00/00/0000');
$("#buttonDownloadBRScan").click(function() {
$windowopen = window.open();
$windowopen.location.href = "https://www.fdibr.com.br/autenticacao/autenticacao/login";
$test = $windowopen.document.getElementById("usuario").innerHTML = "7478704";
})
});
</script>
</head>
<body>
<div class="dataInput">
<label id="labelDateBegin">Data Inicial</label>
<input id="dateBegin" type="date" />
<label id="labelDateEnd">Data Final</label>
<input id="dateEnd" type="date" />
</div>
<br><br>
<button id="buttonDownload">Download</button>
<button id="buttonDownloadBRScan">Download BRScan</button>
</body>
Assuming you have access to that domain in the window you're opening (same origin policy), you have to wait for the window to finish opening first before accessing elements inside.
$("#buttonDownloadBRScan").click(function(){
const w = window.open('https://www.fdibr.com.br/autenticacao/autenticacao/login');
w.addEventListener('DOMContentLoaded', () => {
w.document.getElementById("usuario").innerHTML = "7478704";
});
})
Try something like this:
<input id="yourID" type="button" onclick="open_page()" value="Your Message Here"/>
<script>
function open_page () {
window.open('Your Webpage');
}
</script>
the external site and your internal site have different domain,you can't modify the external site content from your internal site directly.you can use window.postMessage,maybe it would resolve your problem

How to use external Javascript to use onclick event to change document.title?

This code runs immediately once the page is loaded. The onclick event is completely ignored by javascript. What is an easy fix for this because like youtube when you play a video the document.title is updated with a speaker. I want to learn to do that with external javascript because I can do it with internal javascript in the html.
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="animationcss.css">
</head>
<body>
<script src="animation.js"></script>
<input id="changeButton" type="button" value="Change" ></input>
/External Javascript/
var element = document.getElementById("changeButton");
element.onclick = textChange("changetothis");
function textChange(text){
document.title = text;
}
try calling the function after the document is loaded by placing the script tag below the object or making $(document).ready() function,
this code works fine with me
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
</head>
<body>
<input id="changeButton" type="button" value="Change" ></input>
<script src="script.js"></script>
<body>
</html>
and the script is
var el = document.getElementById("changeButton");
el.onclick = function(){
textChange("changetothis");
}
function textChange(text){
document.title = text;
}
You can achieve your desired effect by using an anonymous function, like so:
document.getElementById("changeButton").onclick = function () {
document.title = newTitle;
}
The variable 'newTitle' should be declared & initalized above this code somewhere in order for it to work.

Categories

Resources