Select a default value in a drop-down list:

<select id="ddlColors">
    <option value="white">White</option>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>

<script language="javascript" type="text/javascript">
    var ddl = document.getElementById("ddlColors");
    var val = "green"; // value to set

    for (var i = 0; i < ddl.options.length; ++i) {
        if (ddl.options[i].value == val) {
            ddl.selectedIndex = i;

Create gradient color without using images or CSS:

<script language="javascript" type="text/javascript">
    document.write('<table cellspacing="0" cellpadding="0">');
    for (var col = 0xD0D0D0; col >= 0x606060; col -= 0x010101)
        document.write('<tr height="2"><td width="100" bgColor="#' + col.toString(16) + '"></td></tr>');

Include JavaScript code within an HTML page:

<script language="JavaScript" type="text/javascript" src="/script.js" />

Dynamically insert a link to an external JS file:

var myurl = "http://" + document.domain + "/Scripts/MyScript.js";

var obj = new Object();
obj = document.createElement("<script src='" + myurl + "' language=javascript>");

var arr = new Array();
arr = document.getElementsByTagName("head");
arr[0].insertAdjacentElement("beforeEnd", obj); 

Navigate to another page (equivalent methods):

document.location.href = 'newpage.htm';
window.location = 'newpage.htm';
window.location.href = 'newpage.htm';

Show parts of a URL (an example URL: http://localhost:60564/Test.html)

alert(; // localhost:60564
alert(window.location.hostname); // localhost
alert(window.location.port); // 60564

Open a pop-up window when an image, a button, or an anchor is clicked:

<input type="image" src="/open.gif" alt="Open Window" onclick="javascript: var win ='test.htm', 'WindowName', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=500,height=500,top=5,left=10,screenX=10,screenY=5'); return false;" />

<a href="javascript:var win ='test.htm','WindowName', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=500,height=500,top=5,left=10,screenX=10,screenY=5'); win.focus();">Open Window</a>

<input type="button" value="Open Window" onclick="javascript: var win = open('test.htm', 'WindowName', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=500,height=500,top=5,left=10,screenX=10,screenY=5');" />

Hide and show an element:

// Hide
document.getElementById('ElementId').style.display = 'none';
// Show
document.getElementById('ElementId').style.display = '';

Use 'this' keyword with styles:

<span onmouseover="'red'" onmouseout="'black'">Make me red</span>
<img src="/before.gif" onmouseover="this.src='/after.gif'">

Set the position of an element:

// Hide
var el = document.getElementById('ElementId'); = 10; = 10;