By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,264 Members | 1,277 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,264 IT Pros & Developers. It's quick & easy.

Toggle colour change on click

KeredDrahcir
100+
P: 426
I have a division and I want to click on it to change the colour to red and click on it again to change the colour back to black.
The code I'm using doesn't seem to work and I can't work out what I'm doing wrong. Can anyone help me?

HTML
Expand|Select|Wrap|Line Numbers
  1. <div style="width: 30px; height: 30px; border-style: solid; border-color: #ffffff; border-width: 2px 0 0 2px; float: left; background-color: #000000;" id="a1" onclick="plan('a1');">&nbsp;</div>
JavaScript
Expand|Select|Wrap|Line Numbers
  1. function plan(id){
  2.     var obj = document.getElementById(id);
  3.     (obj.style.backgroundColor == "#000000") ? obj.style.backgroundColor = "#ff0000" : obj.style.backgroundColor = "#000000";
  4. }
Many thanks.
Aug 3 '13 #1

✓ answered by yolshevsky

This works.
Expand|Select|Wrap|Line Numbers
  1. obj.style.backgroundColor = (obj.style.backgroundColor == "rgb(0, 0, 0)") ? "#ff0000" : "#000000";
  2.  
apparently the background property is not a string.

Share this Question
Share on Google+
2 Replies


P: 2
This works.
Expand|Select|Wrap|Line Numbers
  1. obj.style.backgroundColor = (obj.style.backgroundColor == "rgb(0, 0, 0)") ? "#ff0000" : "#000000";
  2.  
apparently the background property is not a string.
Aug 4 '13 #2

KeredDrahcir
100+
P: 426
Fantastic. Works perfectly. Many thanks.
Aug 4 '13 #3

Post your reply

Sign in to post your reply or Sign up for a free account.