Ken Ward's New Java Script Tutorial

Java script functions from text - changing background colours 2

This page shows how a function can be called from java script by using a text link.The previous lesson used "bgColor" to do this, however, the current practice uses "backgroundColor".


 

Try clicking in the boxes, and then click here to bring things back to some semblance of normality (or click the button above).

On this page we are calling a function from a text link. As we are clicking, we don't want to have a real link here. (And some browsers hate it when we don't put a link in). So we have used a '#':

<a href="#" onclick="white()">click ... </a>

We call the function from HTML by using an ONCLICK event. This calls our function:

<script type="text/javascript">

<!--//

function white()

{

document.body.style.backgroundColor="white"

}

//-->

</script>

So when we click on the link we call a function called, in this case, 'white()'. The function has one line of code (for each colour):

document.body.style.backgroundColor="white"

JavaScript is case sensitive!

But java script does care. When written between <script> tags it must be backgroundColor, exactly as written!

Here is the code for this page:

<html>

<head>

<title>Changing background colour style backgroundColor instead of bgColor</title>

<script type="text/javascript"><!--

function red()

{

document.body.style.backgroundColor="red"

}

function blue()

{

document.body.style.backgroundColor="blue"

}

function fuchsia()

{

document.body.style.backgroundColor="fuchsia"

}

function yellow()

{

document.body.style.backgroundColor="yellow"

}

function white()

{

document.body.style.backgroundColor="white"

}

// -->

</script>

</head>

<body>

<table border="0" cellpadding="5"

cellspacing="0">

<tr>

<td style="background-color:red"><a href="#" onclick="red()">red</a></td>

<td style="background-color:#9595FF"><a href="#" onclick="blue()">blue</a></td>

</tr>

<tr>

<td style="background-color:#ff00ff"><a href="#" onclick="fuchsia()">fuchsia</a></td>

<td style="background-color:yellow"><a href="#" onclick="yellow()">yellow</a></td>

</tr>

</table>

</center></div><p>&nbsp;</p>

<form>

<p><input type="button" value="Back to white background" name="B1" onclick="white()"></p>

</form>

</body>

</html>

Next: [Changing foreground colour]

 


Contents

Basic Code

Alerts

New Lines

Text Box Input

Changing Background Colour

Changing fgColor

[If you need to learn more about HTML visit the HTML Tutorial]

I am always pleased to hear from you.
Send your comments to