Forums
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Show / hide div with toggle text – help
Hi I’m trying to code at simple show/hide div like
$(".box").hide();
$(".clickme").show();
$('.clickme').click(function(){
$(".box").slideUp();
_parent = $(this).parent();
_elm = $(_parent).find(".box");
if($(_elm).css('display')=="none"){
$(_elm).slideToggle();
}
});
This is working fine. But I would like to toggle the “clickme text”
Something like this: https://css-tricks.com/snippets/jquery/toggle-text/
But I can’t code it right …
See the following demo i put together
Hi SgtLegend
In your demo I see two click text.
My goal is something like this:
Show box
.....
If I see the content in the “box” the click-text will be “Hide box”
Is this what you are after? http://jsfiddle.net/joshnh/Drrkb/
I have updated the fiddle to respect your goal
@SgtLegend Any reason you are using the each method instead of caching the elements as a variable? I don’t know that much about jQuery, so it is probably something simple.
Right, thanks for that @kgscott284!
The $.each
method simply allows for more flexibility and more maintainable code, personally i always choose it over calling a collection of elements unless its very simple like:
$('element').on('click', function() {
$('input:checkbox').attr('checked', function() {
return !$(this).is(':checked');
});
});
In this case calling the $.each
method would be a waste since we can do a simple evaluation of the :checked
status on the checkboxes, the same concept applies to the box toggle code.
@SgtLegend Would you mind explaining how it allows for more flexible and maintainable code?
@joshuanhibbert
thats exactly what I’m looking for … but I’m using Drupal7 and jQuery 1.4.4
@SgtLegend
It have to be in jQuery 1.4.4
Ah, right, here it is for 1.4.4: http://jsfiddle.net/joshnh/Drrkb/
@joshuanhibbert
so fuc… awesome – tx :-)
No worries :D
I know it’s been a while since my last post which probably seems fishy but I have just been busy, to see what i mean by my above comments see the following jsFiddle which has a built in feature that allows the boxes to open by default.