Dr. Mark Humphrys

School of Computing. Dublin City University.

Home      Blog      Teaching      Research      Contact

Search:

CA216      CA249      CA318

CA400      CA651      CA668


JavaScript



Reference



Where to put the JavaScript code

Client-side JavaScript.
  1. Embedded within the HTML code:
     
    <script language="javascript" type="text/javascript"> 
    (code) 
    </script> 
    

    If you leave out language="javascript" type="text/javascript" probably every browser defaults to JavaScript:

     
    <script> 
    (code) 
    </script> 
    


  2. In separate JS file containing just Javascript code:
     
    <script language="javascript" type="text/javascript" src="file.js" > 
    </script> 
    

    Q. Why might you use .JS files?


  3. Put it in <head> or <body> ?
    Whether embedded in HTML or in JS file: Can be included in <head> or <body>
    If put at end of <body> page may load faster.
    If script uses document.write to insert content, it must appear at a certain location.


  4. One-liners inside certain HTML attributes. See Event attributes.
     <div  onmouseover="fn();" > When mouse over here function is called  </div>
    
     <input  type="button"    value="Click to run function"  onclick="fn();" />
    

    This mixes up Javascript with HTML, which is a bit messy. See more on this later.




Include remote library

You can include a remote library at run-time:

   <script  src="http://remotesite.com/library/file.js" > </script> 

Q. Why might you prefer to use a local copy?



Document Object Model (DOM)




Javascript demos

I remove the header and footer to make it easier to View Source.

Demo HTML (View Source) Javascript (View Source)
Javascript page change demo HTML

(inline)

Minimal size page change demo HTML

(inline)

Javascript menu demo HTML

(inline)

Javascript environment variables demo HTML (inline)
Javascript syntax highlighting HTML JS
Javascript demo - doing calculations on client side HTML (inline)



Debugging

Debugging Javascript can be difficult.
Where do you write output debug info to?
Syntax errors may generate error messages somewhere, but they are not on screen.

Q. Does the client want to see Javascript errors?



Writing output

  

Feeds      w2mind.org

On Internet since 1987.