javascript - Toggle Color based on RGB or Hex values of DOM element -


why following code not toggle element color when button clicked? assumption style.color returning object of sorts , not string. best way correct issue. in advanced!

<!doctype html> <html> <head> <script> function myfunction() { asd=document.getelementbyid("demo") if (asd.style.color!="rgb(255,0,0)") asd.style.color="rgb(255,0,0)"; else asd.style.color="rgb(0,0,0)"; } </script> </head>  <body>  <h1>my first javascript</h1>  <p id="demo"> javascript can change style of html element. </p>  <button type="button" onclick="myfunction()">click me!</button>  </body> </html> 

browser vendors return various versions of style.color value.

from quick test on page (which pasting code javascript console can see yourself):

  • ie8 returns "#888" document.queryselectorall('div[class="user-details"]')[0].currentstyle.color
  • chrome , firefox return "rgb(136, 136, 136)" document.defaultview.getcomputedstyle(document.getelementsbyclassname('user-details')[0], null)['color']

i'm sure i've seen previous version of 1 browser return "rgb(136,136,136)" (without spaces) before.

one way work around inconsistency define colors in css classes instead , toggle between class names.

a very simple demonstration of following code. very simple work if element has single css class. need write utility function check if element has class applied , functions add , remove single class list if design needed multiple classes. these have been written many times before there plenty of examples (search javascript hasclass addclass removeclass) or use existing utility library.

css

.on {     color:#f00; }  .off {     color:#000; } 

javascript

function myfunction() {     var e = document.getelementbyid("demo");      e.classname = e.classname === 'on' ? e.classname = 'off' : e.classname = 'on'; } 

html

<h1>my first javascript</h1>  <p id="demo" class="off"> javascript can change style of html element. </p>  <button type="button" onclick="myfunction()">click me!</button> 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -