I have a set of div pairs (a 'header' and a 'body'). When the user clicks on the header, the next body section should show/hide (and update the +/- icon). All the divs are written to be "shown" on page load but I'd like to "close" some of them and the user can open them if they wish. Just can't get it to work! Code is below if anyone can help!
Sample section:
<div class="expandingSection_head" id="expanderAI">
<img class="imgExpand" src="../images/treeExpand_plus.gif" />
Header text here
</div>
<div class="expandingSection_body">
body text here
</div>
...more pairs of divs like this on rest of page...
Code to toggle:
$(".expandingSection_head").toggle(
function() {
$(this).css('background-color', '#6BA284');
$(this).find('.imgExpand').attr('src', '../images/treeExpand_plus.gif');
$(this).next(".expandingSection_body").slideUp(400);
},
function() {
$(this).css('background-color', '#6BA284');
$(this).find('.imgExpand').attr('src', '../images/treeExpand_minus.gif');
$(this).next(".expandingSection_body").slideDown(400);
});
$("#expanderAI").toggle();
This last line doesn't "toggle" the specified div (i.e. "close" it). Anyone know why? Probably something simple.
Thanks!
The Best Answer isYou need the jQuery and Boostrap Javascript files included in your HTML page for the toggle to work. (Make sure you include jQuery before Bootstrap.)
A toggle key is a key that is used to turn a function on or off, or to switch between two functions. Examples of toggle keys are the caps lock key, number lock key and scroll lock key. A toggle key can also be used as an accessibility option to alternate the input mode of keys.
It won't toggle just by specifying:
$("#expanderAI").toggle();
There should be some event behind it, example:
$('element').click(function(){
$("#expanderAI").toggle();
});
Update:
Try this:
$('#expanderAI').click(function(){
$(this).toggle();
});
upon re-reading the quesiton. i'd change this to a .click() then it should fire your toggle handler that were previously attached.
$("#expanderAI").click();
EDIT:
alright: i just wrote a test script: check it out:
<div id="ToggleMe">Toggle Me</div>
<div id="ChangeMe" style="background-color:Aqua;">Hello WOrld</div>
<script type="text/javascript">
$(function () {
$('#ToggleMe').toggle(
function () {
$('#ChangeMe').css('background-color', '#ff0000');
},
function () {
$('#ChangeMe').css('background-color', '#000000');
}
);
$('#ToggleMe').click();
});
</script>
so, the div i'm changing SHOULD show as aqua, but on page load it's red. b/c the click() event is firing on the document ready.
so put your $('#ToggleMe').click(); in your document ready section after you attach the handlers and it really should work. the proof is right here!
the toggle function doesn't appear to have a use with no parameters:
http://api.jquery.com/toggle/
try using $('#elementID').click();
instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With