Making setBackgroundColor function more generic

Take 0

function setBackgroundColor() {
    document.getElementById('simple2').style.backgroundColor = '#ff33ff';
}

Take 1

Two steps.

function setBackgroundColor() {
    mynode = document.getElementById('simple2');
    mynode.style.backgroundColor = '#ff33ff';
}

Take 2

Two steps. Using variables to define "id" and color.

function setBackgroundColor() {
    var myid = 'simple2';
    var mycolor = '#ff33ff';
    mynode = document.getElementById(myid);
    mynode.style.backgroundColor = mycolor;
}
Example 8.3 - Javascript Events Illustrated - Example 8.3 (Without Styles) |
<p><a href="#" onclick="setBackgroundColor();">Change background color</a></p>
<p id="simple2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc lobortis orci a odio. Donec cursus, felis eu pulvinar ornare, sem turpis dapibus elit, eget laoreet eros quam vel dolor. Ut ante mauris, ullamcorper quis, posuere quis, lacinia a, felis. In tincidunt malesuada pede. Donec varius lacus sed nisi. Donec rhoncus est ac erat. Duis lobortis fringilla eros. Donec volutpat ligula eu neque. In hac habitasse platea dictumst. Donec in massa. Aenean lectus ante, gravida et, luctus id, posuere at, pede. Nam risus orci, rhoncus eu, aliquam ut, interdum ut, orci. Suspendisse rutrum, turpis sed molestie gravida, libero risus iaculis ligula, quis tempor ligula enim vel sem.</p>
  

In style element (<style type="text/css">) within head element:


body {font-family: Calibri,Tahoma,Verdana,Helvetica,sans-serif;}
#simple2 { 
  padding: 1em; 
  border: medium solid black;
  width: 75%;
}

In script element within head element (<script type="text/javascript">):


function setBackgroundColor() {
    myid = 'simple2';
    mycolor = '#ff33ff';
    mynode = document.getElementById(myid);
    mynode.style.backgroundColor = mycolor;
}
 

Copyright © David Heitmeyer