Richie
Richie

Reputation: 41

Changing the color of a div when you click it twice?

I have a link with an onClick command to change the background color. When you click it the color changes fine, but how can I make it so when you click it again the background color changes to normal?

onClick="style.backgroundColor='#3E729F';"

Upvotes: 1

Views: 1788

Answers (2)

Lri
Lri

Reputation: 27613

If you only need to add or remove a background color, you can check if the element has a background color.

<script>
function highlight(e) {
    if (e.style.backgroundColor) {
        e.style.backgroundColor = null;
    } else {
        e.style.backgroundColor = "#ffa";
    }
}
</script>
<div onclick="highlight(this);">a</div>
<div onclick="highlight(this);">a</div>

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

You might define a function in a script element :

<script>
var oldColor;
function switchColor(el) {
   if (oldColor) {
        el.style.backgroundColor = oldColor;
        oldColor = null;
   } else {
       oldColor = el.style.backgroundColor;
       el.style.backgroundColor = '#3E729F';
   }
}
</script>

and call it like this :

onclick="switchColor(this);"

demonstration

Upvotes: 4

Related Questions