Here is my code. I want to toggle classes using addClass
,for some reasons I don't want to use toggleClass
. Problem here I am facing is that css class named selected
is added but its not replaced by not_selected
.isSelected=0
only indicates that td
is selected or not.
<script type="text/javascript">
var isSelected = 0;
$("td").click(function(){
if(isSelected==0)
{
$(this).removeClass('not_selected');
$(this).addClass('selected');
isSelected=1;
}
});
$("td").click(function(){
if(isSelected==1)
{
$(this).removeClass('selected');
$(this).addClass('not_selected');
isSelected=0;
}
});
Below is my css
code:
.selected
{
background: black;
color:white;
font-weight: bold;
}
.not_selected
{
background: white;
color:black;
font-weight: normal;
}
Try condensing the two into a single function. It's possible guaranteed (thanks Barmar!) that one handler is running before the other and then automatically switching it back to the undesired one. This way, it will check for isSelected==0
and isSelected==1
in one swoop.
$("td").click(function(){
if(isSelected==0)
{
$(this).removeClass('not_selected');
$(this).addClass('selected');
isSelected=1;
} else if(isSelected==1)
{
$(this).removeClass('selected');
$(this).addClass('not_selected');
isSelected=0;
}
});