Reputation: 17
I have a a HTML page with a button which shoes hidden content when pressed. I am using jquery code which I have bundled into my HTML page. When I press the button to show the content in the hidden div it works find, however when I press the button again to hide the content nothing happens. If anyone could help me that would be great. Also how would I be able to target multiple buttons. Would I just paste the same jquery code and label it '2' and then '3' and so on for example? Any working examples would be great. Here is my code:
HTML:
<head>
<script>
$(document).ready(function() {
$("#spoiler1").hide();
$("#button1").click(function() {
$("#spoiler1").show(300);
});
});
</script>
</head>
<button id="button1">Adventurer ▼</button>
<div id="spoiler1" style="display:none">
<p>1. Climb a tree<input type="checkbox" /></p>
<p>2. Roll down a really big hill<input type="checkbox" ></p>
<p>3. Camp out in the wild<input type="checkbox" ></p>
<p>4. Build a den<input type="checkbox" ></p>
<p>5. Skim a stone<input type="checkbox" ></p>
</div>
Thanks in advance for any help or advice.
Upvotes: 0
Views: 760
Reputation: 17366
Use .toggle()
instead
$(document).ready(function () {
$("#spoiler1").hide();
$("#button1").click(function () {
$("#spoiler1").toggle('slow');
});
});
Update
And the idea about having mutiple buttons, I've come up with the approach that you should try, use classes
instead of IDs
for the buttons and provide the same ID
to divs
that you want to toggle. This might take some design issues but you can manage and this is just a basic guideline to move forward.
As Markup is too long for mutiple divs so i'm posting only.
JQuery
$(document).ready(function () {
$(".category").click(function () {
$(".show").hide();
var divToShow = $(this).text().split(" ")[0];
$("#" + divToShow).toggle('slow');
});
});
Upvotes: 5
Reputation: 22242
As for multiple button event. Assign a class name to the button so you can select by class.
$('button.toggle-div').click(function(){...});
As for visibility toggle, there are a number of ways.
Use toggle()
in jQuery
. (the most obvious choice, but in practice we could also..)
Use toggleClass()
link to
add/remove a class which has a display:none
css rule. (more flexible, you can toggle other css styles like the font color, background, etc.)
Use some two-way binding JavaScript libraries like knockoutjs or angular. (Probably an overkill for a small application. But it will definitely reduce the amount of coding if it is a large scale.)
Upvotes: 0
Reputation: 114
Use toggle instead:
$('#button1').bind("click",function(){
$("#spoiler1").toggle("fast");
});
Upvotes: 0
Reputation: 5211
$(document).ready(function(){
$("#spoiler1").hide();
$("#button1").click(function(){
if($("#spoiler1").is(':visible')){
$("#spoiler1").slideUp(300);
}
else
{
$("#spoiler1").slideDown(300);
}
});
});
Demo:
Upvotes: 0