Reputation: 14544
Sorry, this was a bad question. I couldn't work out how to delete it. Actual question and solution here:
jQuery - Toggle div class on click
Upvotes: 0
Views: 678
Reputation: 39393
Just use toggle, if all you need is visibility. If you have custom css for hiding sections, use toggleClass. To illustrate
<script type="text/javascript">
$(function () {
$('p').click(function () {
$('#book').toggle();
// In javascript, just like many C-derived languages, you can pass
// the method's pointer to a variable in.
// hidden is the custom class you add and remove from a section
f = $('#great').is('.hidden') ? funky : hacky;
f($(this));
$('#great').toggleClass('hidden');
$('#amazing').toggleClass('man');
alert($('#great').attr('class') + ' ---- ' + $('#amazing').attr('class'));
});
function funky(section) {
$(section).html('this is funky!');
}
function hacky(section) {
$(section).html('this is hacky!');
}
});
</script>
<div id='book' style='display: none'>Hello</div>
<div id='great' class='diz hidden whatever'>Hai</div>
<div id='amazing' class='spider'>Hai</div>
<p>Stackoverflow rules!</p>
If you want the section to start hidden, put style=display: none
to the tag. For your custom hiding/formatting, use toggleClass.
Upvotes: 0
Reputation: 161
There is no need to rebind functions.
Either you bind the click event to a function called toggleSection() which hides the section if it is visible or shows if hidden, or just use this:
$('.section.hidden').click(function() {
$(this).toggle();
});
Upvotes: 1
Reputation: 633
In this case you can just use
$('.section-legend, .section-collapse').click(hidesection);
and
function hideSection() {
$(this).addClass('hidden');
}
Upvotes: 0
Reputation: 2101
jQuery offers an easier way to achieve what you want to do:
That way you don't have to implement the changing by hand, but rather work with one click-binding
If of course you would want to just hide and show an object, you could also use
instead of coding it by hand. That is mostly what Javascript-Frameworks do for you, they implement existing functions, that you can tap into, instead of implementing them yourself. Also cross-browser incompatibilities are taken care of (mostly).
If you really want to use jQuery to its fullest potential, please dig through The jQuery API to get to know all the functions it has to offer. That way you will save a lot of time, that you otherwise would put into developing already existing functions.
Upvotes: 0