Changing multiple object properties simultaneously with JavaScript

The following code is placed in the <head> section of the html file:

<script>

function changeStuff(){
   var box = document.getElementById("box");
   box.style.backgroundColor = "#B2D526";
   box.style.border = "10px solid #98b620";
   box.style.paddingLeft = "150px";
}

function changeBack(){
   var box = document.getElementById("box");
   box.style.backgroundColor = "#D5DEEA";
   box.style.border = "none";
   box.style.paddingLeft = "25px";
}

</script>

The above example uses two functions, one to make the change and one to change it back. In this case, we assign the object we're interested in (box) to a variable and then use the variable to target that object for each property we want to change.

The object (element) you want to change is identified by an ID. Remember, this is unique to that object. In this example, the element containing the code above has been given the ID "box" and the opening tag looks like this: <pre id="box">.

The script is run by clicking a link. Here's the code:

<a href="javascript: changeStuff()">Change stuff</a>

Try the links below to see what happens.

Change stuff | Change back

Note that the JavaScript code is placed "inline" i.e. within the anchor tag. Obviously, this is not ideal if we want to separate the behavioural layer from the structural layer.