Why doesn’t this exercise work ?
var web_page1 ="http://www.thecatmouse.com";
var b1 = document.getElementById("btn1");
b1.onclick=function(){
window.location=web_page1;
};
<form><input type="button" value="Go Searching!" id="btn1" />
</form>
Why doesn’t this exercise work ?
var web_page1 ="http://www.thecatmouse.com";
var b1 = document.getElementById("btn1");
b1.onclick=function(){
window.location=web_page1;
};
<form><input type="button" value="Go Searching!" id="btn1" />
</form>
Why putting it at the end of the BODY tag cause it to work, although it didn’t link to www.thecatmouse.com it linked too http://www.shopusi.com/homepagenew/cat_mouse/index.html ???
How come it wouldn’t work by putting it within the head tags ?
I understand, sorry I didn’t read it over + the stress I’m under doesn’t help
It’s probably because the JS is in the HEAD. The browser processes that JS immediately, and since the BODY doesn’t even exist yet, the document.getElementByID will fail. You need to either tell the browser to wait for the rest of the DOM to load, or put the JS after the elements you need to target.
The best idea is to put the JS in <script> tags just before the closing BODY tag.
Did you even bother reading the first paragraph in my first post?
When a browser reads and HTML document, it goes from top to bottom, like you’d read it. When it gets to the <head>, if it finds any javascript, it will execute it. So if you have something like document.getElementById in there, it’s not going to work, because the browser hasn’t even got to the BODY yet. But… you can tell the browser to wait until it’s finished parsing the body. This is done using window.onload:
function start() {
var web_page1 ="http://www.thecatmouse.com";
var b1 = document.getElementById("btn1");
b1.onclick=function(){
window.location=web_page1;
}
}
window.onload = start;
But you can avoid using window.onload by simply putting all your JS at the bottom of the body. After all, by then the browser knows what there is in the body, so there’s no danger of things like document.getElementById failing.
window.onload is also not very good because it waits for all the images to load and, if there are lots of them, it can mean your javascript gets executed after a very long delay. There are other alternatives that allow you to put your JS in the head, but none is as simple as just putting all your JS at the bottom of the body.