change body color using pure javascript -


hi2all write code change color of webpage when user click div

but doesn't work here code what's wrong

<!doctype html> <html> <head>     <meta http-equiv="content-type" content="text/html" />     <meta name="author" content="gencyolcu" />      <title>untitled 1</title>       <script type="text/javascript">       var x=document.getelementbyid("m");     x.addeventlistener("click",function{         document.body.style.backgroundcolor = "red";     });      </script> </head>  <body >  <div id="m">kfjgflg</div>  </body> </html> 

you should use such as:

<!doctype html> <html>     <head>         <meta http-equiv="content-type" content="text/html" />         <meta name="author" content="gencyolcu" />         <title>untitled 1</title>     </head>     <body>         <div id="m">kfjgflg</div>         <script type="text/javascript">             var x=document.getelementbyid("m");             x.addeventlistener("click",function(){                 document.body.style.backgroundcolor = "red";             });         </script>     </body> </html> 

because have 2 problems in original code:

  • is missing important () after token "function".
  • the javascript recognizes element after page or element has ready. in case, element read recognized if code has after javascript codes recognizes it.

the code above fixes this.

a important observation: in ie's, code can not work, because of use of x.addeventlistener, in case, can transform anonymous function in normal function (with name) , listen addeventlistener (if available) , onclick (recommended old ie's).

in way,the code looks like:

<!doctype html> <html>     <head>         <meta http-equiv="content-type" content="text/html" />         <meta name="author" content="gencyolcu" />         <title>untitled 1</title>                 </head>      <body>          <div id="m">kfjgflg</div>          <script type="text/javascript">             function changecolor(){                 document.body.style.backgroundcolor = "red";             }             var x=document.getelementbyid("m");             if(!!x.addeventlistener){ //if exists                 x.addeventlistener("click", changecolor);             }             x.onclick = changecolor; //it's property, , can set (but in cases not recognized)         </script>     </body> </html> 

here working example code: http://jsfiddle.net/fjorgemota/qcxh3/


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -