Passing values to Javascript functions

So far events have triggered just one action (one function does one thing). JavaScript will allow much more.

The next function takes a string value (some text) passed from an event trigger and puts it in a variable. Then it uses that variable to change the appearance of the whole page.

function changebgcolour(colour) {
    window.document.body.style.backgroundColor=colour;
}
        

There is event handler attached to all three elements below each of which passes a different value to the function:

<p onclick="changebgcolour('green');">Green</p>
<p onclick="changebgcolour('blue');">Blue</p>
<p onclick="changebgcolour('red');">Red</p>
        

Create a new Web page (colours.html) and copy those two chunks of code (the function to the HEAD inside SCRIPT tags and the paragraphs to the BODY. Load the page and click on each word. One function is doing three different things because of the value passed to it by the event trigger.

Almost anything can be used to hold the event trigger. Up to now a few highlighted words have been used or a button. It is useful to give the user clues that something can be clicked on or hovered over but as you can see anything can be made active.

submit to reddit Delicious Tweet