jQuery slideToggle one div at a time instead of all independently
I'm using the function below that toggles divs, and with it, any one of the entry-content divs can be opened or closed independently of all.
What would be great is if only one entry-content div would be open at any time. Clicking a closed entry-title div would close any oth开发者_如何学Cer entry-content div and then open the one clicked. I need to stay with the html markup, as it is created dynamically by Wordpress. Is this possible?
Function:
jQuery(document).ready(function($) {
$(".entry-content").hide('slow');
$(".entry-title").click(function() {
$(this).parent().children(".entry-content").slideToggle(500); });
});
html
<div class="entry-post">
<h2 class="entry-title">Post Title 1</h2>
<div class="entry-content">Lorem Ipsum...
</div></div>
<h2 class="entry-title">Post Title 2</h2>
<div class="entry-content">Lorem Ipsum...
</div></div>
More of the same....
</div>
Just close them all up again every time one is clicked:
jQuery(document).ready(function($) {
$(".entry-content").hide('slow');
$(".entry-title").click(function() {
$(".entry-content").hide();
$(this).parent().children(".entry-content").slideToggle(500); });
});
Example: http://jsfiddle.net/auUxk/
Yes, you can just use this logic:
$(".entry-title").click(function() {
// hide all entry title elements
$('.entry-title').hide();
// show the clicked one
$(this).show();
});
You can adjust it to use toggle instead of hide/show.
I am usually doing this kind of logic by assigning special css classes to elements (its better to have things separated). So when I click element, I add a class to it. But then, when you click another element, you have to elements with that class, but you want only one. So you have to modify it. First remove that class from all elements with it, and then add it to clicked element.
$(".anyAffectedElement").click(function() {
// remove any instances of special class
$('.enabledElement').removeClass('eneabledElement');
// add special class to clicked element
$(this).addClass('enabledElement');
});
^ This is just a general logic how can you deal with things like this. In simple cases, that 'enabledElement' class just adds some special styling (like highlight).
I did not understand those examples which were given by others, but finally i have found the answer in another place, if anyone needs a solution simplier (or different) : http://jsfiddle.net/bipen/zBdFQ/1/
@markratledge - first you need to give id of your divs instead of classes...
$("#link1").click(function(e) {
e.preventDefault();
$("#div1").slideDown(slow);
$("#div2").slideUp(slow);
});
$("#link2").click(function(e) {
e.preventDefault();
$("#div1").slideUp(slow);
$("#div2").slideDown(slow);
});
精彩评论