I created a table with one row and two cells.I am trying to swap the bgcolors of the two cells on button click ,here's my code:
[CODE]
<table>
<tr>
<td bgcolor="red">cell1</td>
<td bgcolor="blue">cell2</td>
</tr>
</table>
<input type="button" value="swap" onclick="swap()"/>
<script type="text/javascript">
var x=document.getElementsByTagName('td');
var temp=new array();
function swap()
{
temp[0]=x[0];
temp[0].style.backgroundColor=x[0].style.backgroundColor;
x[0].style.backgroundColor=x[1].style.backgroundColor;
x[1].style.backgroundColor=temp[0].style.backgroundColor;
}
</script>
</body>
</html>
[ICODE]
But this isn't producing any output on button click,how to implement this?
there is no need for an array (which should be written as new Array, btw) and you are not setting the bgcolor by the style attribute so you can't get it that way either. Simplified:
Code:
<script type="text/javascript">
var x=document.getElementsByTagName('td');
function swap(){
temp=x[0].bgColor;
x[0].bgColor=x[1].bgColor;
x[1].bgColor=temp;
}
</script>
Thanks a lot..
In this case there is just 1 cell getting stored in temp,but when there are more than 1 we must use array so I tried temp=new array(3);
temp[0]=x[0].bgColor and so on but it doesnt give output so eventually i had to use 3 different variables,where m i wrong?
Last edited by cg_chinmay; 05-26-2012 at 06:32 PM..
if you just want to swap between two colors you can do this, regardless of how many tds there are:
Code:
<script type="text/javascript">
var tds=document.getElementsByTagName('td');
function swap(){
for (var i = 0; i < tds.length; i++) {
tds[i].bgColor=tds[i].bgColor=="blue"?"red":"blue"
}
}
</script>