Wickham's HTML & CSS tutorial

Sitemap | Home | Search

Javascript

View in Firefox, Safari, Opera and IE but IE6 often needs different solutions. In general IE7 and IE8 display like Firefox apart from the HTML5 and CSS3 features. The IE9 & above updates are mainly related to HTML 5 and CSS3 issues and display to a large extent like other main browsers. Google Chrome is based on the same WebKit engine as Safari.

Some of the examples are provided just to show problems, others show solutions that work in most major browsers. Use the example that suits you.
red icon problems   gold icon warning: works in some situations or some browsers or needs care to display as you wish   green icon OK in Firefox, Safari, Opera, Google Chrome and IE


Javascript applications

I won't attempt to teach javascript, just to show some applications where the code can be copied and edited to suit your situations. Internet Explorer uses the term ActiveX to cover javascript, although ActiveX is different to javascript in some respects.

Pages with javascript may not validate; this is because validators sometimes find errors with javascript which aren't really errors at all and also because code to play sound may use the embed tag which is still commonly used although deprecated. Look at the page source code for the script but I have shown the code for the body section below for most examples.


Warning that javascript/ActiveX is disabled

1 green icon This javascript is useful at the top of a page to warn viewers who have javascript disabled that it is required for this page. If you have javascript enabled, disable it temporarily to see the warning message

If you have javascript disabled the message in red text should show above.

The code is:-

<noscript><p><span style="color: #ff0000;">Your javascript/ActiveX is disabled but you need it for this page.</span></p></noscript>


Time and date functions

2 green icon The current time and date from the viewer's computer should be shown in the top left corner of the page.

The code for the body tag needs amending:-

<body onload="clock()">

The code for the body is:-

<!--For the script for time which updates see http://www.javascriptmall.com/learn/lesson9.htm or Time update script-->
<div class="time">
<form name="clock" action="">
<table><tr><td>
<input class="inputtime" type="text" name="digits" size="5" value=""/>
</td></tr></table></form>
</div>
 
<!--script for time which stays as the time the page was opened (not used on this page) from http://www.cev.washington.edu/lc/CLWEBCLB/jst/js_datetime.html
<div class="time">
<script type="text/javascript">
var d = new Date()
document.write(d.getHours())
document.write(":")
document.write(d.getMinutes())
</script>
</div>
-->
 
<!--script for date from http://www.cev.washington.edu/lc/CLWEBCLB/jst/js_datetime.html-->
<div class="day">
<script type="text/javascript">
var d = new Date()
var weekday=new Array ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
document.write(weekday[d.getDay()])
</script>
</div>
 
<div class="date">
<script type="text/javascript">
var d = new Date()
var monthname=new Array("January","February","March","April","May","June","July","August", "September", "October", "November", "December")
document.write(d.getDate() + " ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>
</div>

The classes .time and .day and .date in the stylesheet have position: fixed to set the display at the top left corner, but this can of course be edited so that the display is in a position which flows with the remainder of the page. IE6 does not operate position: fixed so a conditional comment just for IE6 to apply position: absolute is in the head section of the page.


Open link in new window of fixed size

3 green icon If you want a link to open a page with a certain width and height that is not full screen, use this code:-
In the head section or at the bottom of the page which has the link:-

<script type="text/javascript">
<!-- Idea by: Nic Wolfe (Nic@TimelapseProductions.com) -->
<!-- Web URL: http://fineline.xs.mw -->
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Begin
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "',
'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=500,left = 100,top = 100');");
}
// End -->
</script>

which will set the new window size 600*500px 100px from the top left corner of your screen, with scrollbars if necessary.

In the link:-

<a href="javascript:popUp('linkedfilename.html')">Your link text</a>

You can set whatever sizes you want for the window.
This link here opens the Links page in a smaller window. Remember that not everyone has javascript or ActiveX enabled, so they won't be able to open your link. (If javascript or ActiveX is disabled it will just open this same page again.)

See also this popup generator.


Curved corners

4 green icon See this example of javascript used to create curved corners.


Sound with play and stop buttons

5 gold icon Here is a javascript version for sound played on mouseclick without opening a sound player window.

If you want an image showing a photo of the music's subject like a band or something else about the sound you have to place a button next to or below the image. Javascript can also be used to provide a stop button. The code is from forums.dealmac.com

Sound Test
 

The script codes have been put at the bottom of the html source code. The validator finds errors with the javascript codes in XHTML 1.0 but not with HTML 4.01; it works in IE and Firefox provided ActiveX and javascript are enabled.


Email addresses concealed from spambots

6 green icon See the code here which shows how to break an email address into separate parts so that a computer spambot has difficulty harvesting your address. It used to be a very good method but some advanced spambots can reassemble the address now; however, few spambots go to the trouble to do it when so many email addresses are easily available, so this method still gives good, but not complete, protection. The safest method seems to be to use a form with PHP processing at your host's server so that your email address is never available for harvesting. See this page.

 

Password protection for a web page link

7 green icon You can show a title for a page and create a login instead of a hyperlink to prevent unauthorised viewing.
The username for the example below is wickham43 and the password is London.
It needs javascript/ActiveX enabled for it to work.

Enter the username and password to see the protected page.

Enter username:
Enter password:

See Dynamic Drive for the javascript code and to obtain the encryption.

I put the script in a separate javascript file password.js so that nearly all validation errors are prevented. There is still one remaining validation error relating to onClick for the submit button which cannot be avoided with XHTML 1.0 doctype but the HTML 4.01 doctype raises no error.

The javascript method above will protect the web page while no one knows the filename but if someone knows the full url with domain name, directory and filename it can be pasted into the browser address bar and bypass the login box, so make sure that the people given the username and password do not broadcast the url to strangers.

Another way to password-protect a web page is to use an htaccess file on your host's server. See Apache.org for details. If you have cPanel on your host's server you can password-protect files or directories with that. (It is probably creating or editing an htaccess file). See cpanel.net. These methods cannot bypass the login box.

You can also password-protect files or folders/directories using PHP scripting.


Expand or collapse page content

8a green icon You can use a javascript controlled button to expand or collapse an area of your page, including text and images.

Click a button below to see how it works (you may need to click twice). Click again to close the section.

green square Yes, all the scripts on this site are free for personal or business use. The only requirement for using them is that you leave the credit information inside the script.

gold square JavaScript is NOT Java. JavaScript is a basic scripting language that allows Web authors to create dynamic pages that react to user interaction.

The javascript file is expandcollapse.js; the script link and modified input tag codes can be seen in the head section of this page and the updated html markup is in the body section.

Free JavaScripts are provided by The JavaScript Source. For the original code and script for this particular script see Expand-Collapse Paragraph.

There's a more advanced method with a link to click saying "more »" at stunicholls.com.


Expand or collapse page content using the <button> element tag

8b green icon You can use a javascript controlled <button> element to expand or collapse an area of your page, including text and images. The code seems to need two clicks on the button at first to get it to work. I'm not sure why this is.

green square Javascript using the <button> element.

The javascript file is expandcollapse.js; the script link and <button> tag codes can be seen in the head section style tag of this page for "Expand or collapse page content" and the html markup is in the body section source code.


Alternate stylesheets

9 green icon One of the most useful uses of javascript is to provide one or more alternative stylesheets, either to give the viewer an alternative style like light text on a dark background instead of dark on light, or to help people with poor eyesight by giving them a stylesheet with larger text. In this last situation you can choose to enlarge only certain bits of text on the page, perhaps only the general text or photo sub-titles which are normally in small font-size but leaving the headings and menus the same size if they are already larger font-size. A browser zoom or larger text button would enlarge everything including images or all text.

I found this tutorial from A List apart very helpful.

There are three different types of stylesheet: persistent which is given no title and will apply with your other persistent stylesheet(s) if you have more than one and also apply with either preferred stylesheet(s) or alternate stylesheet(s). Preferred stylesheet(s) must have a title and must have the same title if more than one. Alternate stylesheet(s) have different titles and will replace only the preferred stylesheet(s).

Here is a typical extract from a typical head section where there is one persistent stylesheet, one preferred stylesheet and two alternate stylesheets, followed by the javascript file link:-

The intention with the above stylesheets is to alter the font-size. The tutorial.css stylesheet contains div sizes, margins, etc. which are common to all requirements. The textnormal.css and alternate stylesheets can have different font-size in the body style to apply to all text or if you want to alter just some styles, then edit only those styles.

Note that use of an alternate stylesheet will disable the whole of a preferred stylesheet(s) so each alternate stylesheet must be a complete replication of a preferred stylesheet apart for your chosen differences. It's not the same as a conditional comment where you may only state the few styles that are different, you have to repeat all of them and edit a few.

The html markup code is placed anywhere you want but preferably somewhere at the top of the page and can be text links as shown in the following code or images showing a small, medium and large A with a side note that these can be clicked to change text size:-

This would appear as:-

Text size: Normal | Medium | Large

which I have only applied to a class="textsize" for these paragraphs with the textnormal.css file only containing .textsize { font-size: small; }, altmedium.css contains .textsize { font-size: medium; }, and altlarge.css contains .textsize { font-size: large; }. The class="textsize" would be unnecessary if you had stylesheets with font-size applied to the body.

The javascript file styleswitcher.js can be downloaded from the A List apart site or here.

There is also a cookie code incorporated into styleswitcher.js so that once a viewer has chosen a font-size it will be remembered when he visits another page with the same options.


Noscript substitution of text or images

10a green icon You can use javascript to show one version of text or images and noscript to show a different version when javascript is disabled. Look at the paragraph below with javascript enabled and then disabled. It has different text and image when seen with or without javascript.

The code the styles is:-

The code the html markup is:-

The javascript file expandscollapsetext.js above contains:-

I put the markup above in a separate file called expandcollapsetext.js to avoid validation errors caused by the javascript.

I believe that document.write( ) is an out of date javascript code but my javascript knowledge isn't good enough to know what the latest code is, but document.write( ) still works. Text and html code inside document.write( ) needs double quotes as in document.write("Text and html code"). Note that html code that has double quotes like <p id="para1a"> that is inside javascript needs single quotes instead of double quotes.


Noscript to show text in expand/collapse script when javascript is disabled

10b green icon This example is a different version of item 8 above so that when javascript is disabled, viewers will see alternative text but when javascript is enabled they will need to click the expand/collapse show/hide button, which can help to minimise content on the viewed page.

Click the button below to see how it works (you may need to click twice). Click again to close the section.

green square Yes, all the scripts on this site are free for personal or business use. The only requirement for using them is that you leave the credit information inside the script.

The code the styles is:-

The code the html markup is:-

The javascript file is expandcollapse.js; the script link and modified input tag codes can be seen in the head section of this page and the updated html markup is in the body section.


Javascript coding generally

The script codes and html codes can be seen in the source code for this page or the following files:-
Time update script
New page popup script
Sound play/stop script.

The javascript code can either be placed in the html file directly within
<script type="text/javascript">...</script>
tags or put in a separate javascript file if the code raises errors when validating the html code. In these situations, especially with large sections of javascript, it's best to put the javascript in a separate external javascript file. Open Notepad and enter the javascript code without the <script> and </script> tags and save it as javascript.js.

In the html file add a link to the javascript file, either in the head section (where the javascript applies to several items on the page or is controlled by an instruction like onClick in the body markup) or in the body markup:-
<script src="javascript.js" type="text/javascript"></script>

Where javascript code is placed in the head section and it causes a delay in the page load it will usually still work if placed at the page bottom just before the </body> tag (as in this page). It will probably mean that the page as a whole is displayed first and the javascript operates afterwards.

An example of the external javascript file emailmung.js for email address protection is:-
emailE='myname'
emailE=(emailE + '@' + 'hotmail.com')
document.write('<a href="mailto:' + emailE + ' ">' + ' Email me' + '</a>')

and the link in the desired position in the body markup is:-
<script type="text/javascript" src="emailmung.js"></script>


Validation of html pages with javascript and the javascript code

See Validation for validating html pages with javascript.

See Links for sites to validate javascript.


Notes

View/Source or View/Page Source in browser menu to see all html code.

The stylesheet for this site which you will probably need to look at is here.

The body of this page has margin: 20px. The examples above are in a containing div with width: 730px; and margin: auto; so that they centralise at large screen resolutions.

A lot of codes have been put in html tags in my examples rather than in a stylesheet or in a style in the head. I have done this for the convenience of the viewer so that most (but not all) codes are in one place and the stylesheet does not always have to be viewed in addition. When coding your own page you should try to put as much as possible in a stylesheet and link with id or class to the html tag.

Remember that when a Doctype is included above the head before the html tag (as it should be) then the overall width of a div is its defined width plus borders, margins and padding widths.

If there are differences between Firefox and IE6 that cannot be overcome with one code, code first to get a satisfactory solution in Firefox then create an IF style which will only apply to IE6:-
for instance, if margin-top: 20px; in Firefox needs to be margin-top: 30px; in IE6 then put the following in the head of the html/xhtml page:-
<!--[if ie 6]> <style type="text/css"> div { margin-top: 30px; } </style> <![endif]-->
or if there are many different styles, create a separate stylesheet:-
<!--[if ie 6]> <link rel="stylesheet" href="ie6.css" type="text/css"> <![endif]-->
IE6 will contain just the amended styles such as div { margin-top: 30px; } and others (no head or body tags or Doctype).

When looking at a page source for this site you may see code like &lt;p>Little Egret&lt;/p> instead of <p>Little Egret</p>. The code &lt; is because in that instance the code is to be displayed on the screen as text. If the < symbol was placed in the code a browser would activate the code and it would not display as text. Such code is not normally required when writing html code tags which are to be activated.

© Wickham 2006 updated 2008


top | Sitemap | prev | next

 

Google
web www.wickham43.net/