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 trialTorger Angeltveit
11,228 PointsHow do i run the same jquery code multiple times?
Hi, i have small code of Jquery, I want to hide and show a element when a button is clicked.
i have this code but it will only hide it and show it once.
$(".product1-readmore").hide();
$("button").click(function(){
$(".product1-readmore").show();
$("button").click(function(){
$(".product1-readmore").hide();
});
});
2 Answers
Chris Shaw
26,676 PointsHi Torger,
The reason your code only appears to work once is because you have a secondary event nested within your main click
event which won't work, instead you want to use a method such as toggle
which triggers either show
or hide
depending on the display state of the element.
See the below for code that will work as expected.
$(".product1-readmore").hide();
$("button").click(function() {
$(".product1-readmore").toggle();
});
One thing to note is a recent study found the show
and hide
methods to be very bad for performance so instead it's better to use a class that gets toggled.
$('.product1-readmore').addClass('inactive');
$("button").click(function() {
$('.product1-readmore').toggleClass('inactive');
});
Happy coding!
Torger Angeltveit
11,228 Pointsahhh, thank you very much. now it works :)
Chris Shaw
26,676 PointsNo worries.
Mark Buckingham
5,574 PointsMark Buckingham
5,574 PointsInteresting read about show/hide.
If using toggleClass() then would you combine it with some CSS to hide the element, for example:
Mark