[javascript] Javascript change Div style

I want that part 1 onclick div style changes and part 2 again on click it comes back to normal. I tried doing so but I failed to achieve the part 2 results.

Following is the Javascript code

function abc() {
    document.getElementById("test").style.color="red";
}

After clicking the test div again, color should come back to defaulr color i.e. black...

This question is related to javascript

The answer is


function abc() {
    var color = document.getElementById("test").style.color;
    color = (color=="red") ? "black" : "red" ;
    document.getElementById("test").style.color= color;
}

Using jQuery:

$(document).ready(function(){
    $('div').click(function(){
        $(this).toggleClass('clicked');
    });
});?

Live example


Better change the class of the element (.regular is black, .alert is red):

function abc(){
  var myDiv = document.getElementById("test");
  if (myDiv.className == 'alert') {
    myDiv.className = 'regular';
  } else {
    myDiv.className = 'alert';
  }
}

you may check the color before you click to change it.

function abc(){
     var color = document.getElementById("test").style.color;
     if(color==''){
         //change
     }else{
         //change back
     }
}

Have some logic to check the color or have some flag,

function abc() {
    var currentColor = document.getElementById("test").style.color;

    if(currentColor == 'red'){
    document.getElementById("test").style.color="black";
    }else{
   document.getElementById("test").style.color="red";

    }
}

A simple switch statement should do the trick:

function abc() {
    var elem=document.getElementById('test'),color;
    switch(elem.style.color) {
        case('red'):
            color='black';
            break;
        case('black'):
        default:
            color='red';
    }
    elem.style.color=color;
}