Toggle script automatically wrapped
I have code
<script>
jQuery(function($) {
$('#toggle1').click(function() {
$('.toggle1').slideToggle('slow');
return false;
});
$('#toggle2').click(function() {
$('.toggle2').slideToggle('slow');
return false;
});
</script>
<a href="#" id="toggle1">header1</a>
<div class="toggle1" style="display:none">content1</div>
<a href="#" id="toggle2">header2</a>
<div class="toggle2" style="display:none">content2</div>
What should I change to get the result when you click on the first heading, the second is automatically collapsed and vice versa
+3
source to share
4 answers
jQuery(function($) {
$('#toggle1').click(function() {
$('.toggle1').slideToggle('slow');
return false;
});
$('#toggle2').click(function() {
$('.toggle2').slideToggle('slow');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="toggle1">header1</a>
<div class="toggle1" style="display:none">content1</div>
<a href="#" id="toggle2">header2</a>
<div class="toggle2" style="display:none">content2</div>
Check the above code.
Where are you doing wrong:
- You cannot include any jQuery library.
- You've added
<script>
JS to your console that shouldn't be there. - You forgot to close the function
jQuery(function($) {
with the help});
at the end.
+1
source to share
<script>
$(document).ready(function(){
var $togglers = $('.toggler');
$togglers.click(function(e) {
e.preventDefault();
$togglers.next().slideUp(800);
$(this).next().slideDown(800);
});
});
</script>
a + div {display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="toggler">header1</a>
<div>content1</div>
<a href="#" class="toggler">header2</a>
<div>content2</div>
+1
source to share
Try,
HTML:
<a href="#" class="toggle" id="toggle1">header1</a>
<div class="toggle1 toggleElem">content1</div>
<a href="#" class="toggle" id="toggle2">header2</a>
<div class="toggle2 toggleElem" style="display:none">content2</div>
JS:
$('.toggle').click(function () {
var currnt = $(this).next(".toggleElem").slideToggle("slow");
$(".toggleElem").not(currnt).slideUp("slow");
});
0
source to share