Frage

I have some mobile navigation that uses a scrollTo function, that once clicked, makes my toggle function only work on the second click. It may have to do the the binding of the scrollTo click, but I can't figure out how to fix it.

HTML:

<div class="nav-bar">
    <ul class="nav">
        <li><a href="#section1">Section 1</a></li>
        <li><a href="#section2">Section 2</a></li>
        <li><a href="#section3">Section 3</a></li>
    </ul>
    <a class="nav-toggle">Menu</a>
</div>
<div class="section-wrap">
    <div id="section1" class="section">Section 1</div>
    <div id="section2" class="section">Section 2</div>
    <div id="section3" class="section">Section 3</div>
</div>

JS:

$('ul.nav a').bind('click',function(event){
    $('ul.nav a').removeClass('on');
    $(this).addClass('on');
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top - 30
    }, 200, function() {
        $('.nav-bar').removeClass('open');
    });
    event.preventDefault();
});

$('a.nav-toggle').toggle(function() {
    $('.nav-bar').addClass('open');
}, function () {
    $('.nav-bar').removeClass('open');
});

See this for a working example of the issue: http://jsfiddle.net/MhSKC/9/

War es hilfreich?

Lösung

At the end of your animate, you remove the open class. Then on the next click of the menu bar, the toggle function tries to remove the open class again, because that's the one of the two toggle functions that needs to execute next. Here's a slightly reworked solution:

http://jsfiddle.net/P4mtC/

$('a.nav-toggle').click(function() {
    $('.nav-bar').toggleClass('open');
});

Andere Tipps

instead of using

$('a.nav-toggle').toggle(function() {
    $('.nav-bar').addClass('open');
}, function () {
    $('.nav-bar').removeClass('open');
});

use

 $('a.nav-toggle').click(function() {
    $('.nav-bar').toggleClass('open');
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top