Alee Raza Memon
Alee Raza Memon

Reputation: 13

Javascript-Using single function instead of multiple

Here the code:

 <script type="text/javascript">

   function ChangeColor1()
   {
    t1.style.backgroundColor = 'pink';
    t2.style.backgroundColor = '';
    t3.style.backgroundColor = '';

   }


    function ChangeColor2()
    {

    t1.style.backgroundColor = '';  
    t2.style.backgroundColor = 'pink';
    t3.style.backgroundColor = '';

    }


    function ChangeColor3()
    {

    t1.style.backgroundColor = '';
    t2.style.backgroundColor = '';
    t3.style.backgroundColor = 'pink';

        }
        </script>

        </head>
        <body>

        <table width="50%" border="1" >

        <tr id="t1" onclick="ChangeColor1();">
        <td>1</td>
        <td>2</td>
        <td>3</td>
        </tr>

        <tr id="t2" onclick="ChangeColor2();">
    <td>4</td>
    <td>5</td>
    <td>6</td>
    </tr>

     <tr id="t3" onclick="ChangeColor3();">
    <td>7</td>
    <td>8</td>
    <td>9</td>
    </tr>
    </table>
    </body>

In this program there are 3 functions are used. I want to do this task using a single function instead of one.

Upvotes: 1

Views: 96

Answers (2)

mplungjan
mplungjan

Reputation: 178010

DEMO

NOTE: Not all browsers will accept t1.style without the document.getElementById

function ChangeColor(row) {
  var idx=row.id;
  for (var i=1;i<=3;i++) {
    document.getElementById("t"+i).style.backgroundColor = (idx==="t"+i)?"pink":""; 
  }
}

using

<tr id="t1" onclick="ChangeColor(this);">
<tr id="t2" onclick="ChangeColor(this);">
<tr id="t3" onclick="ChangeColor(this);">

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

function changeColor(n){
  t1.style.backgroundColor = n == 1 ? 'pink' : '';
  t2.style.backgroundColor = n == 2 ? 'pink' : '';
  t3.style.backgroundColor = n == 3 ? 'pink' : '';
}

... onclick="changeColor(1)" ...

Would be how I'd refactor it. Or better yet make an array of var ts = [t1,t2,t3] then reference ts[n].

var ts = [t1,t2,t3];
function changeColor(n){
  for (var i = 0; i < ts.length; i++){
    ts[i].style.backgroundColor = (i+1) == n ? 'pink' : '';
  }
}

Or you can reference the id directly:

function changeColor(n){
  for (var i = 1; i < 4; i++){
    document.getElementById('t'+i).style.backgroundColor = n == i ? 'pink' : '';
  }
}

You can also take it a step farther and reference the row itself instead of specifying the index as an argument (keeping it generic):

function changeColor(t){
  for (var n = 1; n < 4; n++){
    var tn = document.getElementById('t'+n);
    tn.style.backgroundColor = tn.id == t.id ? 'pink' : '';
  }
}

... onclick="changeColor(this);" ...

Upvotes: 2

Related Questions