I have the following javascript in some pug file:
doctype html
html
//- this is not firing for some reason
head
script(type="text/javascript").
document.addEventListener('DOMContentLoaded', function() {
console.log('ready!')
}, false);
the script only runs when I refresh the page, not when I navigate to the page the script do not fire. I am looking for an event like onNavigate, however I do not see it in the list here: https://www.w3schools.com/jsref/dom_obj_event.asp or here: https://developer.mozilla.org/en-US/docs/Web/Events
Your code should work fine(if you code is written in this way). Don't see a problem.
<!doctype html>
<html>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
console.log('ready!')
}, false);
</script>
</body>
</html>
or
<!doctype html>
<html>
<body>
<script type="text/javascript">
window.onload = function() {
console.log('ready!')
};
</script>
</body>
</html>
Ya know the body OnLoad event occurs after any css and js loads - including external refs.
All you really need is:
<body onload="do_this()">
and then in the script element
function do_this(){
// do sh1t
}
Related
Hello my questions is about how a webpage is loaded! Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
alert("Why?");
</script>
</body>
</html>
I cannot for the life of me figure out why the alert is running before the heading is displayed. It is my understanding that since the alert is right above the closing body tag it will be the last thing run. Why is the page waiting for me to close out the alert before displaying the heading?
Thanks for the help!
Edit: I ran this code in firefox rather than chrome and it worked how I wanted it to - the heading displayed first before the alert ran.
You need to execute your script after the page loads with
<body onload="script();">
An external script will execute before the page loads.
<body onload="script();">
<h1>Waiting</h1>
<script type="text/javascript">
function script() {alert("Why?");}
</script>
</body>
You can use setTimeout() to show the alert after a few seconds (when the page should have loaded).
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
setTimeout(function(){
alert("Why?");
}, 1000);//wait 1000 milliseconds
</script>
</body>
</html>
You can check if the header (the h1 tag) is there and only alert if it is there.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1 id="header">Waiting</h1>
<script type="text/javascript">
var x;
x = setInterval(function(){
if(document.getElementById("header")){
alert("Why?");
clearInterval(x);
}
}, 100);
</script>
</body>
</html>
The simplest workaround code without using JQuery I could write is this. Please check it.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
window.onload = function(){
setTimeout(()=>{
alert("Why?");
},10)
}
</script>
</body>
</html>
The cleanest way to do this seems like it would be to put your javascript in a separate file, and load it with the defer attribute. This will cause it to fire after the DOM loads (technically, just before DOMContentLoaded, but it doesn't work consistently across browsers unless there is a src attribute, which is why you would need to move it to an external file.
<script src="myScript.js" defer></script>
Oddly, adding some CSS to your heading could also affect this since JS is supposed to execute in order after any pending CSS.
The timeout function or a $(document).ready() function will do what you need in theory, but a timeout could need to be adjusted based on the complexity of the page, and if you aren't already using jQuery, you probably won't want to add it just to use $(document).ready().
I want to do a quick javascript check from within the head tag, like so:
<html>
<head>
...
<script>
document.body.classList.remove("no-js");
document.body.classList.add("js");
</script>
</head>
<body class='no-js'>
...
</body>
</html>
This doesn't work. Cannot read property classList of null, which...fair enough. If I move the <script> tag into <body>, everything works, but I want the <script> tag in <head>.
What are my options?
EDIT: I should have been much clearer about the error. I realize the problem is that body hasn't loaded when I'm trying to to add the class. However, I was using a bit of Modernizr originally and it was somehow able to modify the body class from within the head and I don't think it was using window.onload or anything like that.
Run the code after body is loaded. There are several approaches to solve the problem:
Move the code into a named function defined in global context and call it in onload.
<html>
<head>
...
<script>
function load() {
document.body.classList.remove("no-js");
document.body.classList.add("js");
}
</script>
</head>
<body onload="load();" class='no-js'>
...
</body>
</html>
Or move code to DOMContentLoaded event listener callback in order to call after dom elements are loaded.
<html>
<head>
...
<script>
document.addEventListener("DOMContentLoaded", function() {
document.body.classList.remove("no-js");
document.body.classList.add("js");
});
</script>
</head>
<body class='no-js'>
...
</body>
</html>
Or move the entire script tag to the end of the page.
<html>
<head>
...
</head>
<body class='no-js'>
...
<script>
document.body.classList.remove("no-js");
document.body.classList.add("js");
</script>
</body>
</html>
At the time the javascript is executed there is no body tag, because the browser hasn't gotten around to it yet. You need to either add the script tag in the body, or add it as an event to execute when the document has loaded. See DOMContentLoaded for an example.
I'm attempting to create a very simple HTML document with an even less complex $(document).ready() function. However.... nothing in the function will fire. I've set alerts and breakpoints (in Chrome's debugger) and nothing works. Below is the markup.
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" />
<script>
alert('outside');
$(document).ready(function() {
alert('here');
});
</script>
</head>
Neither alerts work. Not sure what I'm doing wrong here.
change <script src="http://code.jquery.com/jquery-1.11.0.min.js" /> to
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
alert('outside');
$(document).ready(function() {
alert('here');
});
</script>
you forgot to close the arches. and the closing tag of script.
I am trying to grab an element (a button) and add an event listener on it.
Whenever I run
var button = document.getElementById('clickMe');
console.log(button); // null
I checked that my javascript file is loading and checked that everything is case sensitive. Here is my html and JS Files:
HTML:
<!doctype html>
<html>
<head>
<script src="js/timer.js"></script>
</head>
<body>
<button id='clickMe' type='button'>Hello</button>
</body>
</html>
JS
var button = document.getElementById('clickMe');
console.log(button);
function buttonClicked () {
alert('the button was clicked');
}
button.addEventListener('click', buttonClicked);
function timerComplete () {
alert('timer complete');
}
setTimeout(timerComplete, 2000);
The most common errors I have found was camel casing getelementbyid which I did.
Does anyone know why I keep getting null? Is it trying to grab the element before it is loaded?
Your Javascript code is executed before the Button is added to the DOM. You could change your HTML to this:
<!doctype html>
<html>
<body>
<button id='clickMe' type='button'>Hello</button>
<script src="js/timer.js"></script>
</body>
</html>
Or even better, if you don't mind making your JS code a bit more complex you could wait for your dom elements to be loaded before executing that part of the code:
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('clickMe');
console.log(button);
});
If you use this JS you can put back your script tag back to the head
I'm working on a simple page that uses only <canvas> within the <body> of the page. All of the content is to be loaded through javascript. I am having trouble with using the document in my javascript and I was wondering if anyone could point me in the right direction of using <script> tags. Here is my main question:
What is the appropriate placement of <script> for a function loaded with window.onload
Here is the code I am working with:
index.html
----
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="window.js" type="text/javascript"></script>
</head>
<body>
<canvas>Canvas is not supported by your browser!</canvas>
</body>
window.js
----
Window = function(doc, win)
{
this.doc = doc;
this.win = win;
this.initialize();
}
Window.prototype =
{
initialize: function()
{
this.doc.documentElement.style.overflow = 'hidden';
this.doc.body.scroll = "no";
this.resize();
this.win.addEventListener('resize', this.resize.bind(this));
},
resize: function()
{
_canvas = this.doc.querySelector('canvas');
_canvas.width = this.win.innerWidth;
_canvas.height = this.win.innerHeight;
}
};
window.onload = new Window(document, window);
In all the tests of this script I have run, the only instance where it works is when the <script> is placed after the initial <body> tag. When I place the <script> in the <head> it gives me an error saying:
Uncaught TypeError: Cannot set property 'value' of null
Is it not a possibility for the sake of a clean looking document to have <script> be in the <head>?
Any clarification or direction on what the proper practice is would be greatly appreciated!
Script tags should go at the bottom of the page typically. This ensures all content has loaded and is ready for interaction...
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas>Canvas is not supported by your browser!</canvas>
<script src="window.js" type="text/javascript"></script>
</body>
</html>
If you don't put the script in after the element, as far as your script is concerned, that element does not exist. It needs to be in the bottom, or at least after the canvas element.
In your case, it should be in the bottom, after the <canvas> element.
It really doesn't matter where your JS files are loaded. Your problem is that the JS files could possibly load before your DOM is fully drawn. I've had pages where JS at the bottom of the page was executing before the browser was done loading the middle. That's why every JS framework contains something to check if the DOM is ready or not. in jQuery you would use ready
$(document).ready(function() { alert('My DOM is loaded!'); });
Outside of jQuery, you could use DOMContentLoaded. Put this at the bottom of your window.js file and you can load it in your header without issue.
document.addEventListener("DOMContentLoaded", function(event) {
new Window(document, window);
});