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 trialShreyas Sreenivasa
7,804 PointsjQuery 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
231,236 PointsIt 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
21,689 PointsYou 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
Billy Bellchambers
21,689 PointsBilly Bellchambers
21,689 PointsI was not aware of the speed arguments that's great to know as well.
Thanks for pointing that out
Shreyas Sreenivasa
7,804 PointsShreyas Sreenivasa
7,804 PointsThanks Steven Parker. The slow sure makes it look cool!