Help needed with javascript

Associate
Joined
14 Jan 2004
Posts
1,518
Location
Wiltshire
This is starting to do my head right in...

I'm starting on a new project and thought i would try and do things right from the start. My usual use of JS is to stick it inline with the html, which i know is baaaad. Not all my JS goes inline of course, just the event handlers, which call a function contained in a seperate script file.

So i'm now trying to get my event handlers to work without any inline js at all like i ought to... I have a js file like this for example
Code:
document.getElementById('myid').onmouseover = myFunc

function myFunc() {
   alert('Wow that's clever!')
}

i include this file in the head of my html file, and then in the body of the html file is the element with id of myid.

The problem is that the element doesn't exist when the script is run so i get a document.getElementById("myid") is null error!

I presume i'm being a bit retarded and missing something really obvious cos i've spent ages trying to make it work right, and the only thing that works for me is to take the <script> tags out of the document head and put them at the end of the body, so that by the time it runs, the elements are there...

If someone could explain what i SHOULD be doing then i'd be really grateful!!

Thanks :)
 
I think its something to do with using .innerHTML for the element. I did something similar a while ago, sure you can adapt it to un a function. If you want to to the next stage and make your html ultra neat - without any js - then have a look at JQuery.
 
Thanks for that :)

Your example is how i already code my pages, and what i was looking for was a way to remove ALL the js from my markup. Having a quick look at JQuery prompted me to search google slightly differently and i've now found a script that will fire once the DOM is ready: http://www.hunlock.com/blogs/Are_you_ready_for_this Also, window.onload works, placing everything else inside a function called by this event - the DOM ready script just happens sooner than onload if there are slow loading parts of the page.

I'm sure i tried using window.onload and had no luck... but maybe i'd written document.onload or something else that doesn't happen??

Anyway, thanks for the JQuery suggestion, that pointed me in the right direction :D
 
Back
Top Bottom