What´s wrong reading a xml file? - javascript

This is the simple html file for reading an xml
<!DOCTYPE html>
<html lang="es">
<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>simple script javascript</title>
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="scripts/lector.js"> </script>
</head>
<body>
<h1>"web is running"</h1>
<input type="file" id="file-input" />
<h3>Contenido del archivo:</h3>
<pre id="contenido-archivo"></pre>
</body>
and the lector.js is as follows:
function leerArchivo(e) {
var archivo = e.target.files[0];
if (!archivo) {
return;
}
var lector = new FileReader();
lector.onload = function(e) {
var contenido = e.target.result;
mostrarContenido(contenido);
};
lector.readAsText(archivo);
}
function mostrarContenido(contenido) {
var elemento = document.getElementById('contenido-archivo');
elemento.innerHTML = contenido;
}
document.getElementById('file-input')
.addEventListener('change', leerArchivo, false);
document.getElementById('file-input').addEventListener('change', leerArchivo, false);
console.log(contenido);
returning this error:
Cannot read property 'addEventListener' of null
What´s wrong ?

This is returning null:
document.getElementById('file-input')
Because the code is executing before the element exists on the page. JavaScript is processed in the order it's found in the HTML document, even before the full document is finished loading.
You can move the JavaScript to the end of the page:
<!DOCTYPE html>
<html lang="es">
<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>simple script javascript</title>
<script src="scripts/jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>"web is running"</h1>
<input type="file" id="file-input" />
<h3>Contenido del archivo:</h3>
<pre id="contenido-archivo"></pre>
<script src="scripts/lector.js"></script>
</body>
(The jQuery library can still load at the beginning of the page if you want because it doesn't immediately try to interact with the page, it just initializes itself. But since your script tries to interact with the page, it needs to wait until the page loads.)
Alternatively, since you're loading jQuery anyway, you can use it to easily wait until the document is ready. Something like this:
$(function () {
document.getElementById('file-input').addEventListener('change', leerArchivo, false);
document.getElementById('file-input').addEventListener('change', leerArchivo, false);
console.log(contenido);
});

Related

Why JS Event handlers are not working for elements created at runtime?

document.querySelector("#fire_button_creator_button").addEventListener("click",function () {
document.querySelector("body").appendChild(document.createElement("button")).innerText="now click me,i am fire button";
})
document.querySelector("#fire_button_creator_button+button").addEventListener("click",function () {
document.querySelector("p").innerText="i am fired";
})
<!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 id="fire_button_creator_button">fire button creator</button>
<p></p>
</body>
</html>
I want to creat a button in runtime that can do somthing. Somthing like in my code it inject some text inside <p> </p> tag "i am fired". But i am getting errore. But why?. What is the solution(in vanilla javascript of course)?
document.querySelector("#fire_button_creator_button").addEventListener("click",function () {
const button = document.createElement("button");
document.querySelector("body").appendChild(button).innerText="now click me,i am fire button";
button.addEventListener("click",function () {
document.querySelector("p").innerText="i am fired";
})
})
You have to add the event listener AFTER the new button element is created.
You can do that like the code sample above or other way. The only important part is to do AFTER it is created, so an actual event listener is attached to an actual html element
You can just assign the eventListener to the createdElement immediately instead of selecting it again (which won't work in your case, as the element doesn't even exist yet).
document.querySelector("#fire_button_creator_button").addEventListener("click",function(){
const button = document.createElement("button")
button.innerText="now click me, i am fire button"
button.addEventListener("click",function(){
document.querySelector("p").innerText="i am fired";
})
document.querySelector("body").appendChild(button)
})
<!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 id="fire_button_creator_button">fire button creator</button>
<p></p>
</body>
</html>

JavaScript isn’t working when linking .js file to .html file

I've been learning HTML, CSS & javascript these last few weeks. All the previous coding experience I've had is with C++ from my CS courses so I'm new to front end development.
I wrote some javascript in the HTML index page and the functions work properly. However, when I add it into an external .js file, the program stops working.
Here's the index.html file:
<!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="stylesheet" href="/style.css"/>
<title> Progress Bar </title>
</head>
<body>
<audio id="music" src="trax/coldWorld.wav" controls></audio>
<div class="progress_bar" id="progress_bar">
<div class="progressed" id="progressed"></div>
</div>
</body>
<script src="/audio.js"></script>
</html>
The .js file:
var music = document.getElementById('music');
var progressed = document.getElementById('progressed');
var progress_bar = document.getElementById('progress_bar');
music.ontimeupdate = function(e) {
progressed.style.width = Math.floor(music.currentTime *100 / music.duration) + "%";
}
progress_bar.onclick = function(e) {
music.currentTime = ((e.offsetX / progress_bar.offsetWidth) * music.duration);
}
You can try moving the script tag inside the body tag and correcting the relative path
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
<script src="./audio.js"></script>
</body>
</html>

load an external js file before script in body executes (without jQuery)

I have a site that should first load external js codes before it executes code in the dom but i wont work. Everytime my external codes load after the js in the body tag what caused problems like undefined classes and variables
index.html
<!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>Site</title>
<link rel="stylesheet" href="./style.css">
<script src="./project/load.js"></script>
</head>
<body>
<h1>project</h1>
<div id="project"></div>
<script src="./script.js"></script>
</body>
</html>
./project/load.js
window.onload = function() {
var links = ["./project/script1.js", "./project/script2.js", "./project/script3.js"];
for(var link of links) {
var script = document.createElement("script");
script.src = link + "?0";
script.setAttribute("onerror", "reload(this)");
document.head.append(script);
}
}
I tried also with 'addEventListener('DOMContentLoaded', function() {...});' but it did work either.
I hope you can help me.
EDIT 1:
request order
./project/load.js
./script.js
./project/script1.js
./project/script2.js
./project/script3.js
Load your javascript with defer attribute. Replace your HTML with below. The "defer" attribute allows the javascript is run only after the page loading is complete. Meaning the DOM is available
<!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>Site</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>project</h1>
<div id="project"></div>
<script src="./project/load.js" defer></script>
<script src="./script.js" defer></script>
</body>
</html>
References and further read
https://www.sitepoint.com/introduction-jquery-deferred-objects/
https://www.w3schools.com/tags/att_script_defer.asp
Here is what i've done. Please look at this below
HTML
<!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>Site</title>
</head>
<body>
<h1>project</h1>
<div id="project"></div>
<script src="load.js" defer></script>
<script src="script.js" defer></script>
</body>
</html>
Javascript - load.js
(function(){
var dom = document.getElementById("project");
if( dom !== null ){
dom.innerHTML = "<p>Iam load.js " + new Date().toString() + "</p>";
console.log("Iam load.js " + new Date().toString());
}
})();
Javascript - script.js
(function(){
var dom = document.getElementById("project");
if( dom !== null ){
dom.innerHTML = dom.innerHTML + "<p>Iam script.js " + new Date().toString() + "</p>";
console.log("Iam script.js " + new Date().toString());
}
})();
Output
You can see that the order in which i've added the script loads first.

make a redirect button in html with javascript

Here is the code I am attempting to use and embed in a Google Sites page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Please follow the link below</title>
<script>
var urls = [
"http://www.kittenwar.com/",
'http://heeeeeeeey.com/',
'http://eelslap.com/',
'http://www.staggeringbeauty.com/',
'http://www.omfgdogs.com/',
'http://burymewithmymoney.com/',
'http://www.fallingfalling.com/',
'http://ducksarethebest.com/',
'http://www.republiquedesmangues.fr/',
'http://www.trypap.com/',
];
function goSomewhere() {
var url = urls[Math.floor(Math.random()*urls.length)];
window.location = url; // redirect
}
</script>
</head>
<body>
</body>
</html>
How do I make this work so that a button will appear in my Google Sites page that will randomly assign you to one of the listed array of links?
By adding a simple button and calling the javascript function. And you need to do some adjustments in your google sites account. You can refer this link to do the changes accordingly in your account.
http://www.thelandscapeoflearning.com/2014/05/did-you-know-google-sites-no-longer.html
AND
https://help.mofuse.com/hc/en-us/articles/226313408-Redirect-Setup-Google-Sites
var urls = [
"http://www.kittenwar.com/",
'http://heeeeeeeey.com/',
'http://eelslap.com/',
'http://www.staggeringbeauty.com/',
'http://www.omfgdogs.com/',
'http://burymewithmymoney.com/',
'http://www.fallingfalling.com/',
'http://ducksarethebest.com/',
'http://www.republiquedesmangues.fr/',
'http://www.trypap.com/',
];
function goSomewhere() {
var url = urls[Math.floor(Math.random() * urls.length)];
window.location = url; // redirect
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Please follow the link below</title>
</head>
<body>
<button onclick="goSomewhere();">Redirect</button>
</body>
</html>
In body
<button onclick="goSomewhere();">Click me</button>

change body color using pure javascript

hi2all i write code which change the color of webpage when the user click the div
but doesn't work here is my code what's wrong with it
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
<script type="text/javascript">
var x=document.getElementById("m");
x.addEventListener("click",function{
document.body.style.backgroundColor = "red";
});
</script>
</head>
<body >
<div id="m">kfjgflg</div>
</body>
</html>
You should use something such as:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
</head>
<body>
<div id="m">kfjgflg</div>
<script type="text/javascript">
var x=document.getElementById("m");
x.addEventListener("click",function(){
document.body.style.backgroundColor = "red";
});
</script>
</body>
</html>
Because you have two problems in your original code:
Is missing a important () after the token "function".
The Javascript only recognizes a element after the page or element has ready. In this case, the element only is read to be recognized if your code has after the Javascript Codes that recognizes it.
The code above fixes this.
A important observation: In some IE's, this code can not work, because of the use of x.addEventListener, in this case, you can transform the anonymous function in a normal function (with a name) and listen with addEventListener (if available) and onclick (recommended for old IE's).
In this way,the code looks like:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
</head>
<body>
<div id="m">kfjgflg</div>
<script type="text/javascript">
function changeColor(){
document.body.style.backgroundColor = "red";
}
var x=document.getElementById("m");
if(!!x.addEventListener){ //If exists
x.addEventListener("click", changeColor);
}
x.onclick = changeColor; //It's a property, and ALWAYS can be set (but in some cases is not recognized)
</script>
</body>
</html>
Here is a working example with this code: http://jsfiddle.net/fjorgemota/qCXH3/
If you had opened your JavaScript error console it would have told you that you cannot access the property/method addEventListener of undefined.
You need to look for the element m after the DOM tree has been built. Either place into a function which gets called on DOMContentLoaded:
document.addEventListener('DOMContentLoaded', function() {
/* ... */
}, false);
or place your script at the end of your <body>.

Categories

Resources