Javascript HTML: Generating HTML and Embedding Javascript in HTML

This page covers the following topics:

Embedding Javascript in HTML
Embedding Javascript Directly in HTML: A Button Click Example
Generating HTML With Javascript
Embedding HTML in Javascript

Embedding Javascript in HTML



The way that's most often used to store javascript is to place it in a .js file, make that file accessible via your server (you can check with your browser that you can get to the script), then embed a special link to your script in the head part of your html.

If you want your javascript to run when the page loads, the easiest thing to do is add a window.onload function. This ensure that the page is loaded properly by the time your javascript runs.

Here's an example that illustrates all these points.

Suppose we have a file called test.js, as follows.


// A simple javascript function
function hello() {
    alert('hello');
}

// Let's make the function run
// when the page finishes loading.
window.onload=hello;




In the same directory on my computer, I've created a file called test.html, like this:

<html>

<head>
<title>Test Page</title>

<script language="javascript" src="test.js"></script>

</head>

<body>
Test Page.
</body>

</html>




Now if I open test.html with my browser, I get this:



If I wanted this to run from a webserver (as you usually do), I'd upload the .js file and make sure it was accessible via a url such as http://www.caveofprogramming.com/scripts/test.js. I can then change my HTML like this:

<html>

<head>
<title>Test Page</title>

<script language="javascript" src="/scripts/test.js"></script>

</head>

<body>
Test Page.
</body>

</html>




If I upload this page to my server and access it with my browser, it works just as before.

Embedding Javascript Directly in HTML: A Button Click Example



Or of course, you can just embed your javascript directly in your HTML. This is sometimes handy if you just want to insert a little bit of javascript that won't be re-used anywhere else.

Here's an example HTML page that pops up an alert when a button is clicked.

<html>

<head>
<title>Test Page</title>

<script language="javascript">

function greet() {
    alert('hello');
}

</script>

</head>

<body>

<input type="button" value="Click Me" onclick="greet()" />

</body>

</html>






Generating HTML With Javascript



Often you want to generate some HTML with javascript. It's best not to go overboard with this if you can help it -- your code can end up nasty and confusing if you're not careful. But of course, these days you can find entire huge applications written in javascript.

We'll look here at an example of generating a table in javascript. Here I've used ordinary javascript, however if you're going to do a lot of this kind of thing, it'll be well worth your while to check out one of the free javascript libraries such as jQuery. In spite of the imposing name, jQuery is just a big javascript file that gives you various helpful functions.

<html>

<head>
<title>Test Page</title>

<!-- Might as well have some nice styling -->
<style>

table.data
{
    border: 1px solid gray;
    width: 200px;
}

table.data td
{
    padding: 6px;
}

</style>

<script language="javascript">

// Here's some data.
var data = [
    ['Fruit', 'Color'],
    ['apple', 'green'],
    ['banana', 'yellow'],
    ['orange', 'orange']
];

// Here's a function that formats data
// passed to it in the above format
// as a table. The HTML is returned
// as a string.
function createTable(data) {
    var html = '';
    
    // Assume data is an array of arrays,
    // containing strings.

    html += '<table class="data">';
    
    // Step through the rows of the data.
    for(var row in data) {
        var rowData = data[row];
        
        if(row == 0) {
            html += '<tr style="font-weight: bold;">';
        }
        else {
            html += '<tr>';
        }
        
        // Step through the columns in
        // this row.
        for(var col in rowData) {
            var colData = rowData[col];
            
            html += '<td>';
            html += colData;
            html += '</td>';
        }
        
        html += '</tr>';
    }
    
    html += '</table>';
    
    return html;
}

// This function takes the formatted HTML
// and inserts it into the document as
// 'child' HTML of the specified element.
function insertHTML(id, html) {
    var el = document.getElementById(id);
    
    if(!el) {
        alert('Element with id ' + id + ' not found.');
    }
    
    el.innerHTML = html;
}

// This function ties things up.
function run() {
    var html = createTable(data);
    
    insertHTML('tabledata', html);
}

// Run everything when the document loads.
window.onload = run;

</script>

</head>

<body>

<div id="tabledata"></div>

</body>

</html>






Embedding HTML in Javascript



What if you want to embed some HTML in javascript? We've already done that above, contcatenating bits of html to form a whole table. If you want to embed literally a pre-formatted block of HTML in javascript, you're probably best off using quotes around each line (or you can have one really long line if you must!). It is possible to use multiline strings in javascript; just end each line with a backslash. While this works, it goes against the javascript standard specification. Does that matter? I really don't know.

The following example embeds HTML both ways.


<html>

<head>
<title>Test Page</title>


<script language="javascript">

// This is the 'standard' way of doing things:
var html1 = 
'<div style="width: 100px; height: 100px; background-color: green">' + 
'Test 1' + 
'</div>';

// This way works, but goes against the standard:
var html2 = 
'<div style="width: 100px; height: 100px; background-color: red"> 
Test 2 
</div>';

function run() {
    document.getElementById('test1').innerHTML = html1;
    document.getElementById('test2').innerHTML = html2;
}

// Run everything when the document loads.
window.onload = run;

</script>

</head>

<body>

<div id="test1"></div>
<div id="test2"></div>

</body>

</html>