getElementById/InnerHTML Function not Working - javascript

I'm playing around with Javascript to get back in the swing of things for my second semester web class that recently started, and I've run into an issue getting getElementById and innerHTML to work.
Basically, I want to populate an empty h1 with an Animal name
function favAnimal()
{
document.getElementById("animal").innerHTML="cat"
}
<h1 id="animal" onload="favAnimal()">Favourite Animal Placeholder</h1>
The above does not change anything. If the h1 is empty the result is the same. I've also tried with a <div> to rule out an issue using specific elements.
All help is appreciated and thanks in advance!

An <h1> tag does not have an onload event handler so your function is never being called.
You can use the onload handler for the <body> tag or set up some other event handler to assign your function to.
If you want your code to be triggered when the document is loaded, you can use one of these:
window.addEventListener("load", favAnimal); // all page resources loaded
document.addEventListener("DOMContentLoaded", favAnimal); // HTML done parsing
If you just want your script to be executed right after your <h1> tag has been loaded, you can just place a call to the script right after the tag. The page is parsed/executed in order so that any script will always be able to reference HTML elements that come before it in the document:
<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>
Here are some of the things I'm aware of that have a load event:
window
<img>
<body>
<iframe>
<link>
<script>
<embed>
<object>
<video>
<audio>
XMLHttpRequest
And, pretty much any other HTML tag that has a src or href attribute except <a>. The idea is that if the tag is loading some external resource, then there is a load event to know when it is done loading that external resource. If the tag is not loading an external resource, there is probably not a load event for it.

The load event is only dispatched on resources, such as the document, images, ...
If you want to run some script just after an element has been parsed, just add a script element after it:
<script>
function favAnimal() {
document.getElementById("animal").innerHTML = "cat";
}
</script>
<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>

What is happening here that ur script file executed earlier than the html renders. So it is not able to locate the element as it is not rendered yet. Browser provides events like onload ,unload. Here u need onload
`Document.addEventListener("DOMContentLoaded",init);
Function init (){
//ur code
}`

Related

Javascript adding <script> tag after page loads

Got a little problem here. Basically, I'm trying to add a script tag after the page loads.
This is what I am doing:
index.php:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getad()
{
$.post('assets/getad.php', "ad", function(response) {
response = response.replace('document.write','document.getElementById("ad").innerHTML = ');
eval(response);
console.log(response);
});
}
getad();
</script>
<div id="ad"></div>
</body>
</html>
getad.php:
<?php
echo file_get_contents("http://ads1.qadabra.com/t?id=a823aca3-9e3c-4ddd-a0cc-14b497cad85b&size=300x250");
?>
You can find a demo here: http://dev.cj.gy/game/
As you can see, the #ad div DOES get filled with the correct script tag, but it doesnt actually run, If I edit the page to include the script tag right at page load, it does run.
Yes, <script> tags cause execution when parsed as part of the main document; they don't execute from being written to innerHTML.
You can create an executing script element outside of that initial parse using the DOM method of calling createElement('script'), setting its src/content and adding it to the document. This is what jQuery's getScript does.
However it wouldn't do you much good because the next script, that ads1.qadabra.com is document.writeing to the page, also itself calls document.write.
You could work your way around both of these calls at the client side (ie without getad.php), by assigning your own custom function to document.write that, instead of writing to the loading page, attempts to extract the source of the script tag passed to it, and load that in a DOM-created script element.
But in general these are scripts designed to work synchronously at document load time; anything you do to try to force them to run in a way they weren't intended to is likely to be fragile and stop working when the ad network change anything.
If you want to load a third-party ad without pausing the loading of the parent document, I suggest putting it in an iframe.

How to execute Javascript from external HTML

If I have a button that executes the code
$('#main').load('welcome.html');
and in welcome.html I have a button that executes the code
$('#main').load('otherpage.html');
the Javascript isn't executed, regardless of whether that function is on the parent file's HTML code or the child's.
How can I get a Javascript function to work from externally loaded HTML files?
EDIT
Here's a bit more of a sample...
Homepage:
<body>
<div id="main"></div>
</body>
<script>
document.onLoad(){
$('#main').load('welcome.html');
}
function show(file){
$('#main').load(file+'.html');
}
</script>
welcome.html page:
Test
...however when the Test button is clicked, test.html is not loaded into the Main div.
EDIT 2
Here is what the current state is and what the issue is - exactly.
I've uploaded the bones of the code to PasteBin.
When the 'grid' button is clicked, the content changes and the footer changes.
However, the footer, which has URLs based on Javascript, comes up with the error:
Uncaught SyntaxError: Unexpected token ILLEGAL
...when trying to access the 1i.html page.
There's a difference between test the variable and 'test' the string:
Test
Probably should be:
Test
It is important to understand that when loading script into page via AJAX that the main page has already gone through document.ready . Thus, any code you load will fire immediately.
If the code you load precedes the html it references, it will not find that html when it fires.
Placing the code after the html in remote page will resolve this issue
Check jQuery.live() and jQuery.on().
Maybe your eventhandler is wrong. When you import new markup via load() or ajax(), you have to initialize the handlers from new document. The easiest way is using jQuery.on or jQuery.live() instead of jQuery.click().
$('MYBUTTON').live('click', function(){
$('#main').load('your_url.html')
})
or use the callbackfunction to (re-)initialize the buttons event.
A better solution is this: Just add the target_url to buttons rel attribute...
<button rel="YOUR_URL.html">Open Page</button>
$('button[rel]').live('click', function(){
$('#main').load($(this).attr('rel'));
})

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

I'm trying to do something fairly simple, but for the reason of me probably not being good enough to search documentation, I can't get this to work.
I have a functioning inline JS that looks like this:
<A title="Wolfram IP Calc" href="javascript:txt=prompt('Enter%20IP%20address,%20e.g.%2010.20.30.40/29','1.2.3.4/5');%20if(txt)%20window.open('http://www.wolframalpha.com/input/?i='+txt);void(O);">Compute!</A>
For various reasons, I'm trying to seperate the JS, and this is where I hit a snag.
I've created the following test page that gives me the error Uncaught TypeError: Cannot call method 'addEventListener' of null:
<HTML> <HEAD profile="http://www.w3.org/2005/10/profile"> <script type="text/javascript">
var compute = document.getElementById('compute');
compute.addEventListener('click', computeThatThing, false);
function computeThatThing() {
txt=prompt('Enter%20IP%20address,%20e.g.%2010.20.30.40/29','1.2.3.4/5');
if(txt) {
window.open('http://www.wolframalpha.com/input/?i='+txt);
}
}
</script></HEAD>
<BODY>
<A title="Wolfram IP Calc" id="compute" href="javascript:void(O);">Test</A>
</BODY>
</HTML>
The only thing I've been able to find that points to a problem like that is that addEventListener can't work with <A> but should handle <IMG> (which suits me fine as I'm going to pour this on some images), so I tried adding the following to no avail:
<img id="compute" src="http://products.wolframalpha.com/images/products/products-wa.png" />
Thanks in advance for pointing out what I'm doing wrong. It is probably glaringly obvious, but I have close to zero experience with JS and I have gone mostly by cargo culting when I've needed it until now.
Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...
element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.
MDN
Solutions:
Put the scripts in the bottom of the page.
Call the attach code in the load event.
Use jQuery library and it's DOM ready event.
What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...
ready docs
Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag.
window.onload vs document.onload

onload and Jquery ready(). Do they work on any DOM? such as table or div?

I need to put a dynamic content on a div using javascript script. This div is on the top of the page so it will load first before other things below it. And there are really lot's of things down there. So, when I put the script on the ready() or onload, the div will be empty for 2 -3 seconds while other things are displayed. So, I tried putting the onload or ready() to this div.
//example div, which is on the header part of the page
<div id="cont1">
something goes here
</div>
//... and there are a lot of other things going down here.
I tried putting the onload="alert('test')" on the div tag
<div id="cont1" onload="alert('test')">
and also the jquery method
<script>
$("cont1").ready(function(){
alert("test");
});
</script>
Both methods don't work, as the alert is triggered only after the whole page is displayed.
but if I put the alert("test"); script immediately after closing the above div, it works fine (as the other things on the page is not displayed yet when the alert is showing).
<div id="cont1">
something goes here
</div>
<script>
alert("test");
</script>
But this method is kind of a bad design isn't it? So, any other way to achieve this?
If you want a javascript action to fire after a specific DOM element has loaded, simply place it immediately after the element, as you noted:
<div id="cont1">
something goes here
</div>
<script>
alert("test");
</script>
Some may disagree, but this is not bad design. As long at whatever occurs in this script pertains only to elements which occur prior to it in the HTML document, everything should be kosher. The DOM is loaded linearly in the order it appears in the document, so there is no case in which the script coming after #cont1 would occur prior to #cont1. If the script is lengthy, you could put it in a function in a header include then call the function there instead.
onload and the meta-event of "ready" apply the the entire DOM document, not just any DOM node, which is what you are attempting here.
I would stick with jQuery's $(document).ready(...) for code that requires the DOM to be present.
onload is unfortunately on the window only.
However, I have written a jQuery plugin called waitForImages that will fire a callback when images have loaded inside any container.
This is a bit half way but you can have a img of a single pixel same color as the background at the end of the div and have an onload on the img.

Difference between onload() and $.ready?

Can you list the difference between onload() and $(document).ready(function(){..}) functions in the using jQuery?
the load event (a.k.a "onload") on the window and/or body element will fire once all the content of the page has been loaded -- this includes all images, scripts, etc... everything.
In contrast, jquery's $(document).ready(...) function will use a browser-specific mechanism to ensure that your handler is called as soon as possible after the HTML/XML dom is loaded and accessible. This is the earliest point in the page load process where you can safely run script that intends to access elements in the page's html dom. This point arrives earlier (often much earlier) than the final load event, because of the additional time required to load secondary resources (like images, and such).
The main differences between the two are:
Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document.ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded. Hence, the functions in jQuery's ready event will get executed once the HTML structure is loaded without waiting for the resources.
We can have multiple document.ready() in a page but Body.Onload() event cannot.
Document.ready() function triggers as soon as HTML DOM loaded. But the onload() function will trigger after HTML DOM, all the body content like images loaded.
body.onload() cares about both HTML structure and assoicated resources where as document.ready() cares only about the HTML structure.
onload() fires when all the content (everything) on the targeted eleement is fully loaded like CSS, images etc.
$.ready indicates that code in it need to be executed once the targeted elements content loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
.
Ex(body onload):
<body onload="loadBody()">
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body
Ex(onload on an element):
<img src="w3html.gif" onload="loadImg()" width="100" height="132">
<script>
function loadImg() {
alert("Image is loaded");
}
</script>
Ex3 ($.ready):
<script type = "text/javascript">
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
Onload take care about DOM and resources: it checks if images are loaded, script are ready to run and much more.
$.ready simply check if we have read the full DOM of the page.
Please check out this link for more explain and example: http://dailygit.com/difference-between-document-ready-and-window-load-in-jquery/

Categories