I have TD elements with anchor tag inside them and divs which I want to be revealed when the anchor tag is clicked. Also, I want others to close when any one of them is clicked, if it;s open already.
HTML:
<td>
<a href="#"><img src="images/1.jpg" /></a>
<div class="test"><p>test</p></div>
</td>
<td>
<a href="#"><img src="images/1.jpg" /></a>
<div class="test"><p>test</p></div>
</td>
I tried with this JQuery but for some reason I have to click twice for it to show the div the first time, and if I then click on the second one the first one doesn’t close. I don’t need to add any classes.
<script type="text/javascript">
$(document).ready(function() {
$('.test').hide();
$('td a').on('click', function() {
var state = $(this).next('.test').is('.open');
if (state) {
$(this).removeClass('active').next('.test').removeClass('open').show();
}else{
$(this).addClass('active').next('.test').addClass('open').hide()
.siblings('.test').removeClass('open').show().end()
.siblings('.test').not(this).removeClass('active');
}
});
});
</script>
You can do it without saving state using toggleClass() to toggle the
.activeclass and toggle() to show/hide the current testdiv.In addition I also use not() to hide all other
test divswhich are not the current one.DEMO – Toggle Divs
I used the following HTML in the DEMO