html - Changing CSS Style Using Javascript -


i trying change width of bar when click on button; it's not working. have tried copying code, replacing ids , rewriting code, don't know why it's not working.

<!doctype html> <html>     <head>         <meta http-equiv="x-ua-compatible" content="ie=8,ie=9" />         <title>page title</title>         <script type="text/javascript">             var bar = document.getelementbyid("bar");             function load(){                 bar.style.width = "500px;";             }         </script>         <link rel="stylesheet" type"text/css" href="style.css">     </head>     <body>         <div id="mainwrapper">             citadel goal             <div id="shell">                 <div id="bar"></div>             </div>             <form><input type="button" value ="click" onclick="load();"/></form>         </div>     </body> </html> 

two issues:

  1. you're trying retrieve bar element before exists, bar variable null. move getelementbyid call into load function, you're not trying element until after exists.

  2. the style value shouldn't have ; in it. e.g.:

    bar.style.width = "500px;"; // remove ---------^ 

working example: live copy

<!doctype html> <html> <head>     <script type="text/javascript">         function load() {             var bar = document.getelementbyid("bar");             bar.style.width = "500px";         }     </script>     <!-- stylesheet here, replaced since          don't have stylesheet -->     <style>         #bar {             border: 1px solid #aaa;         }     </style> </head> <body>     <div id="mainwrapper">         citadel goal         <div id="shell">             <!-- note: added div otherwise                  had no height; presumably stylesheet gives height -->             <div id="bar">x</div>         </div>          <form>             <input type="button" value="click" onclick="load();" />         </form>     </div> </body> </html> 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -