1

It's a simple javascript command to get the classname to change when the page loads. What am I doing wrong that it isn't working? http://jsfiddle.net/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>

2 Answers 2

3

A 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 be getElementsByClassName (notice the s). Also, since it'll return a collection of elements, you will need to iterate over it with a for loop.
Sign up to request clarification or add additional context in comments.

1 Comment

good to know. I think I will just stick with getElementById. And thanks for catching the dash. smh
0

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.

3 Comments

thank you! if your id is "mydiv" wouldn't you getElementById('mydiv')?
I think I did everything you said but it still doesn't seem to work. jsfiddle.net/wtH2Y/6 any ideas?
I am sorry, I had provided the wrong id. Can you check my edited answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.