Reputation: 23
I am trying to create a link which when clicked shows some info inside a div that was previously hidden. If the link is clicked again it hides the div. So in otherwords a basic toggle functionality.
Before the link is clicked the anchor text is "Show Details", once clicked the anchor text changes to "Hide Details". The problem is, when clicked again, it doesn't change back to "Show Details", it stays at "Hide Details". How can I achieve that?
Here's my code:
<style type="text/css">
.hiddenDiv { border: 2px solid #ccc; width: 500px; height: 300px; }
</style>
<script type="text/javascript">
$(document).ready(function() {
$('.hiddenDiv').hide();
$('.button').click(function() {
$('.button').html('Hide Details');
$('.hiddenDiv').toggle();
});
});
</script>
<a href="#" class="button">Show Details</a>
<div class="hiddenDiv">
<h2>Lacoste Shirt</h2>
<p>This is a shirt with a small alligator logo sewen on the chest area.</p>
</div>
Upvotes: 2
Views: 101
Reputation: 23
You can get rid of $('.hiddenDiv').hide();
by changing your style to
.hiddenDiv { border: 2px solid #ccc; width: 500px; height: 300px; display:none; }
Upvotes: 0
Reputation: 93694
Instead of .click()
there's a .toggle()
event handler:
$('.button').toggle(function () {
// First click, show
$(this).html('Hide Details');
$('.hiddenDiv').show();
}, function () {
// Second click, hide
$(this).html('Show Details');
$('.hiddenDiv').hide();
});
Alternatively, use your `.hiddenDiv' class - both to show/hide, and to act as a flag...
<style type="text/css">
/* Note the display: none */
.hiddenDiv { display: none; border: 2px solid #ccc; width: 500px; height: 300px; }
</style>
<script type="text/javascript">
$(document).ready(function() {
// Don't need this anymore: $('.hiddenDiv').hide();
$('.button').click(function() {
var toggleMe = $(this).next();
// Don't need to show/hide anymore
toggleMe.toggleClass('hiddenDiv');
$(this).html(toggleMe.hasClass('hiddenDiv') ?
'Show Details' : 'Hide Details');
});
});
</script>
Upvotes: 1
Reputation: 3234
Replace
$('.hiddenDiv').toggle();
$('.button').html('Hide Details');
with
$('.hiddenDiv').toggle();
$('.button').html($('.hiddenDiv').is(':visible') ? 'Hide Details' : 'Show Details');
Edit: In the case that you have multiple button/hiddenDiv combos on the page (as I suspect), you'll need to do this instead:
$(document).ready(function() {
$('.hiddenDiv').hide();
$('.button').click(function() {
var $button = $(this);
var $div = $button.next('.hiddenDiv');
$div.toggle();
$button.html($div.is(':visible') ? 'Hide Details' : 'Show Details');
});
});
Upvotes: 1