0

I am trying to make an interactive web page with the css part and javascript separated from the html document.

sandbox.html (part of it):

    <body>
        <nav class="unify-bg">
                <ul>
                        <li><a id="ipsum" style="top:-90px">Ipsum</a></li>
                </ul>
        </nav>
    </body>

sandbox.css (part of it):

nav li a{
    float:left;
    margin: 0 5px;
    color: #e4b05c;
    color: white;
    font-weight: bold;
    width: 120px;
    height: 100px;
    background-color:#e4b05c;
    position: relative;
    top:-90px;
}

sandbox.js (part of it):

window.onload = function () {
    document.getElementById("ipsum").addEventListener("mouseover", function () {
        ipsum = this;
        var t = setInterval(function () {
            move(ipsum, t);
        }, 10);
    }, false);
}

function move(element, interval) {
    var pos = element.style.top.replace("px", "");
    if (pos > -10) clearInterval(interval);
    else {
        pos = parseInt(pos) + 10;
        element.style.top = pos + "px";
    }
}

somehow if I remove the inline style "top:-90px" from the list element (since the style is already in the *.css anyway), the javascript stops working. Can anyone explain why please and help me solve the problem? Thank you!

3
  • 2
    It "stops working" because element.style.top will return an empty string (the element doesn't have a style set after all). See developer.mozilla.org/en-US/docs/Web/API/… to get the computed style. Commented Apr 6, 2014 at 6:45
  • @FelixKling Yes but why will it return an empty string. Are you saying window.onload runs as soon as the window is loading?? If this is the case why won't it work if I put the javascript under the nav element?? without the window.onload (that is starting from document.getElement... and not forget to remove the closing curly bracket from the window.onload's anonymous function) Commented Apr 6, 2014 at 6:54
  • 1
    "but why will it return an empty string" Because element.style returns the inline style of elements. If you don't set any inline style, it can only return an empty string. "Are you saying window.onload runs as soon as the window is loading" I didn't say anything about window.onload, but the function is called after the document is completely loaded. Commented Apr 6, 2014 at 6:56

1 Answer 1

1

element.style only returns inline styles. Hence, without an inline top, it is an empty string,

If you want all applied styles, use getComputedStyle: window.getComputedStyle(element).top.

Sign up to request clarification or add additional context in comments.

Comments

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.