Reputation: 21
I am trying to change the width of a bar when I click on the button; but it's not working. I have tried copying the code, replacing the ids and rewriting the code, but I 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>
Upvotes: 1
Views: 106
Reputation: 1073968
Two issues:
You're trying to retrieve the Bar
element before it exists, so your bar
variable is null
. Move the getElementById
call into the load
function, so you're not trying to get the element until after it exists.
The style value shouldn't have the ;
in it. E.g.:
bar.style.width = "500px;";
// Remove this ---------^
Working example: Live Copy
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load() {
var bar = document.getElementById("Bar");
bar.style.width = "500px";
}
</script>
<!-- Your stylesheet was here, replaced with this since
we don't have your stylesheet -->
<style>
#Bar {
border: 1px solid #aaa;
}
</style>
</head>
<body>
<div id="mainwrapper">
Citadel goal
<div id="Shell">
<!-- Note: I added something to the div as otherwise it
had no height; presumably your stylesheet gives it height -->
<div id="Bar">x</div>
</div>
<form>
<input type="button" value="click" onclick="load();" />
</form>
</div>
</body>
</html>
Upvotes: 4
Reputation: 13250
You function should be as this way;
function load(){
var bar = document.getElementById("Bar");
bar.style.width = "500px";
}
The reason is that initializing the property dosent know what does the "bar"
contain if you does it outside the function so its better you always define it inside the fucntion.
Upvotes: 0
Reputation: 67
Initialize bar Variable in to the Load Method rather than outside.
function load() {
document.getElementById("Bar").style.width = "500px";
}
try Above Code.
Upvotes: -1