Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

troy beckett
troy beckett
12,035 Points

help with some jquery/javascript code???

HI,

I was looking through a javascript tutorial on the internet today and was trying to understand the code. What the code simply does is open an close a menu when a button is clicked but I just couldn't get my head round the javascript/jquery code even though it looked simple:

heres the code:

        $(function() {
            var menu = $("#menu");
            var clicked = false;
            $( "a.menu-trigger" ).click(function() {
                if(clicked){
                    menu.removeClass("menu-open");
                    clicked=false;
                }else{

                    menu.addClass("menu-open");
                    clicked=true;
                }
            });
        });

code someone possibly explain how this code works I can't really understand how the code would ever each the the else part of the else if part of the code.

1 Answer

Hey troy beckett,

What's happening is that the jQuery code is attaching a click event handler to the anchor link that has class menu-trigger. Whenever the anchor is clicked, the clicked variable is being toggled between true and false which would open and close the menu. So, when you first click that anchor link, it is going to go to the else statement because clicked is currently false. It'll add the class menu-open to the element with the id of menu which I'm sure adds some additional CSS to the menu and set clicked to true. When it is clicked again, it'll remove that class because the if-statement will be executing, so that that additional CSS is removed (closing the menu) and clicked will be set to false again. Does that make sense?

troy beckett
troy beckett
12,035 Points

thanks that really help me out marcus really apprectiate you taking the time I knew it was simple and I was way over thinking it, great explanation

Anytime, Troy! Happy Coding! :)