Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Trying to create a slide-out navigation, but it only runs once.

<div class="nav-wrap">
                <div id="nav">
                    <input type="button" value="X" class="close-button" onclick="closeNav();" />
                    <ul class="links-container">
                        <a href="index.html"><li class="link-item">Home</li></a>
                        <a href="item1.html"><li class="link-item">Item1</li></a>
                        <a href="item2.html"><li class="link-item">Item2</li></a>
                    </ul>
                </div>
            </div>

            <div class="header">
                <p class="logo" href="index.html"><a href="index.html">Text</a></p>
                <img src="images/menu.svg" class="nav-button" onclick="revealNav();" />
            </div>
#nav {
    background-color: dodgerblue;
    padding: 20px;
    right: -360px; 
    position: absolute;
}
/* global window */
/* global document */

var nav = document.getElementById("nav");
var position = -360;

function revealNav() {
    var timer = setInterval(revealNav, 30);
    if (position >= -10) {
        clearInterval(timer);
    } else {
        position += 10;
        nav.style.right = position + "px";
    }
}

var position2 = -10;

function closeNav() {
    var reverseTimer = setInterval(closeNav, 30);
    if (position2 <= -360) {
        clearInterval(reverseTimer);
    } else {
        position2 -= 10;
            nav.style.right = position2 + "px";
    }
}

1 Answer

Daan Schouten
Daan Schouten
14,454 Points

Not exactly sure about this, but you initially define position to be -360. After it's run once, that value is going to be different, since its value gets updated in your functions. Shouldn't you reset it before running it again?