Image

JavaScript

How to embed Javascript code in HTML

Javascript can be included in HTML by whether embedding it to the HTML file itself, or by calling an external file.

There are few options to include Javascript code into HTML, but current best practice is as in the example below;

<script type="text/javascript">
    window.alert("Hello World")
</script>

The above example using type and MIME type, when called from anywhere in the HTML page will pop up an alert with the Hello World text.

How to maximize browser window using Javascript

The key to maximizing the browser window in Javascript is the window.resizeTo() function, which would resize the window to any specified size. The function somehow needs to get the screen’s width and height to be supplied as parameter, and the window itself need to be moved to the top left corner of the screen using the window.moveTo() function so that it will be displayed in full.

The following example will maximize the browser window as the page loads:

<html>
<head>
	<script language="JavaScript">
		window.moveTo(0, 0);
		window.resizeTo(screen.width, screen.height)
	</script>
</head>
</html>

The browser window will maximize if a user click on the URL as in the following example:

<html>
<head>
	<script language="JavaScript">
		function maximizeme(){
			window.moveTo(0, 0);
			window.resizeTo(screen.width, screen.height)
		}
	</script>
</head>
<body>
	<a href="javascript:onclick=maximizeme()">Maximize</a>
</body>
</html>

The function seem to longer be supported by modern browsers

How to import Javascript code from external file in HTML

If your Javascript code is too big, or just for readability and management purpose, it’s best to include Javascript codes from an external file. This method is also good for re-usability purpose.

The code below will load the Javascript code stored in myscript.js to the calling file.

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

How to execute Javascript using HTML hyperlink

One of the way to dynamically execute Javascript codes is by using hyperlink. The trick is to use a URL starting with javascript: , followed by the Javascript code itself.

The URL can be in image, link, or CSS style, and in the example below an alert will pop up when the link is clicked;

<a href="javascript:window.alert('Red Alert')">
Click here
</a>

How to display non-Javascript page for browser with no Javascript support

When a browser doesn’t support Javascript, or simply have it disabled, it’s best to include an alternative non-Javascript content for the page to remain functional.

This is made possible with the noscript tag, and the example below will pop up the alert if Javascript is enabled or supported, and display the text instead if it doesn’t.

<script type="text/javascript">
    window.alert("I support Javascript")
</script>
<noscript>
    I do not support Javascript
</noscript>

Top