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

Shreyas Sreenivasa
Shreyas Sreenivasa
7,804 Points

jQuery click function works only once.

Hey there! I'm building a website but for some reason my click function works only once.

My jQuery:

$('.sub-header .dropdown .dropbtn').click( function() {
   $('.sub-header .dropdown .dropdown-content').show();
   $('.sub-header .dropdown .dropbtn').click( function() {
       $('.sub-header .dropdown .dropdown-content').hide();
   } )
} );

My fiddle: https://jsfiddle.net/rqbskz2y/

Thank you in Advance!

2 Answers

Steven Parker
Steven Parker
216,135 Points

:point_right: It actually works every time. Try putting the argument "slow" in the .show() and .hide() calls to see.

What it's actually doing is adding an additional click handier (which calls .hide()) each time it runs. If you really want to manipulate the click handler inside the handler, you might want to use .click() in combination with .off(), or use .one(). But there's a simpler way to get what you're after.

What you probably want is more like this:

$('.sub-header .dropdown .dropbtn').click( function() {
    $('.sub-header .dropdown .dropdown-content').toggle();  // add "slow" argument for cool effect
} );
Billy Bellchambers
Billy Bellchambers
21,689 Points

I was not aware of the speed arguments that's great to know as well.

Thanks for pointing that out

Shreyas Sreenivasa
Shreyas Sreenivasa
7,804 Points

Thanks Steven Parker. The slow sure makes it look cool!

Billy Bellchambers
Billy Bellchambers
21,689 Points

You have made this more complicated that is necessary.

Try using the the .toggle() function instead to switch between visible and hidden more easily.

   $('.dropbtn').click( function() {
       $('.sub-header .dropdown .dropdown-content').toggle();

    } );

Should give you the results your after.

Hope that helps