It's a simple javascript mand to get the classname to change when the page loads. What am I doing wrong that it isn't working? /
<html>
<head>
<style>
.away {
margin: 30px 0 0 0 !important;
position:fixed;
-webkit-transition: margin 0.6s;
-moz-transition: margin 0.6s;
-o-transition: margin 0.6s;
}
.in {
margin:0;
position:absolute;
}
</style>
<script>
window.onload = function pre-loader() {
document.getElementByClassName('away').className = 'in';
};
</script>
</head>
<div class="away">
this should slide up when the page loads
</div>
It's a simple javascript mand to get the classname to change when the page loads. What am I doing wrong that it isn't working? http://jsfiddle/wtH2Y/4/
<html>
<head>
<style>
.away {
margin: 30px 0 0 0 !important;
position:fixed;
-webkit-transition: margin 0.6s;
-moz-transition: margin 0.6s;
-o-transition: margin 0.6s;
}
.in {
margin:0;
position:absolute;
}
</style>
<script>
window.onload = function pre-loader() {
document.getElementByClassName('away').className = 'in';
};
</script>
</head>
<div class="away">
this should slide up when the page loads
</div>
Share
Improve this question
asked Jul 17, 2013 at 1:37
stevenspielstevenspiel
6,01914 gold badges63 silver badges90 bronze badges
2 Answers
Reset to default 3A few things:
- Function names cannot have dashes in them. Rename your function.
If you're using a named function, I wouldn't assign it to a property this way. Either make it anonymous or assign it like so:
function foo() { ... } window.onload = foo;
Otherwise, you won't be able to call
foo()
.getElementByClassName
should begetElementsByClassName
(notice thes
). Also, since it'll return a collection of elements, you will need to iterate over it with afor
loop.
Because the function is document.getElementsByClassName
and not document.getElementByClassName
. It returns an Array. So you need to get the first element and apply the class. Like this...
document.getElementsByClassName('away')[0].className = 'in';
To make it simple, why don't you assign an id to the div
<div class="away" id="mydiv">
and then use document.getElementById
. Like this...
document.getElementById('mydiv').className = 'in';
It is much simpler and easy to use.