WordPress Underscores, toggling class with mouseup doesn’t seem to work

I’m using Underscores as my base theme for a site, and I really dig that it includes a workable mobile navigation element as a part of the theme. But this is essentially a one-page site, and the navigation doesn’t “de”-toggle when a link is clicked… because it’s not leaving the page.

So I wrote a little script.

Read More

The php-generated-HTML is essentially this (simplified for this post):

<nav id="site-navigation" class="main-navigation toggled" role="navigation">
    <button class="menu-toggle" aria-controls="mobile-menu" aria-expanded="true"><i class="fa-bars fa"></i></button>
    <div class="menu-main-nav-container">
         <ul id="primary-menu" class="menu nav-menu" aria-expanded="true">
             <li class="menu-item"><a href="LINK">Link 1</a></li>
             <li class="menu-item"><a href="LINK#anchor-on-the-page">Link 2</a></li>
             <li class="menu-item"><a href="LINK#different-anchor-on-the-page">Link 3</a></li>
        </ul>
    </div>
</nav>

And here is the script I wrote:

<script type="text/javascript">
    $('.main-navigation.toggled li.menu-item a').mouseup(function(){
        $('.main-navigation.toggled').removeClass('toggled');
        $("button").attr("aria-expanded","false");
        $("#primary-menu").attr("aria-expanded","false");
    });
</script>

I’m sure there’s something obvious I’m overlooking, but I don’t see it.

Related posts

2 comments

  1. How is your whole page setup? If this javascript isn’t running from the footer you may need to wrap your javascript in a document.ready. It might be running when the elements aren’t rendered yet and the mouseup event might not get attached.

    Try this:

    <script type="text/javascript">
        $('document').ready(function(){
        $('.main-navigation.toggled li.menu-item a').mouseup(function(){
            $('.main-navigation.toggled').removeClass('toggled');
            $("button").attr("aria-expanded","false");
            $("#primary-menu").attr("aria-expanded","false");
        });
        });
    </script>
    

    Here’s a fiddle.
    http://jsfiddle.net/zsecLnd6/

    If this doesn’t work try putting a

    alert('test');
    

    Inside the mouseup and document ready function to see if its being run at all.

  2. OK. Here’s what it was, and I don’t know why, but when I removed '.main-navigation.toggled' it worked. Doesn’t make sense to me because those classes are definitely there, but I also don’t care … because it worked. 🙂

    Thanks for your help, folks!

Comments are closed.