Invalid jQuery menu
If I click on the current element, it should turn on and off and close all others if it is open. When I click on menu1 it just keeps open. I want to use features like when it is open it should close, when it is closed it should open. Please view the url
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(".toggle_container").hide();
$("li.trigger").click(function() {
$(".toggle_container").hide();
$(this).next(".toggle_container").slideToggle("slow,");
$("li.trigger").removeClass("active");
$(this).addClass("active");
return false;
});
});
</script>
<ul>
<li class="trigger" id="t1">Menu 1</li>
<li class="toggle_container">Menu 1 content</li>
<li class="trigger" id="t2">Menu2</li>
<li class="toggle_container">Menu2 content</li>
<li class="trigger" id="t3">Menu3</li>
<li class="toggle_container">Menu3 content</li>
</ul>
I'm not sure what your question is, but I see an extra comma at the end of the third line of your code ( ...slideToggle("slow,")
). It probably shouldn't be.
EDIT: After checking the provided url, I can now see what the problem is. First, you must add a new style for the class .toggle_container
:
li.toggle_container { display: none; }
This prevents the initial display of the submenu. Then you have to consider inside the jQuery script if you click on an active or inactive link:
$(document).ready(function() {
$("li.trigger").click(function() {
$(this).next(".toggle_container").slideToggle("slow");
if (!$(this).hasClass("active")) {
$(".toggle_container").hide();
$(".active").toggleClass("active");
$(this).toggleClass("active");
}
return false;
});
});
What is it.
a source to share
You can simply extend jQuery with toggleClass
like below:
//extend jquery
(function($) {
$.fn.toggleClass = function(check, replace) {
return this.each(function() {
if ($(this).hasClass(check)) {
$(this).removeClass(check);
$(this).addClass(replace);
} else {
if ($(this).hasClass(replace))
$(this).removeClass(replace);
$(this).addClass(check);
}
});
};
})(jQuery);
So you can do things like this:
<input type="button" value="Toggle"
onclick="$('#myDiv').toggleClass('expanded','collapsed')"/>
a source to share
Here's a simpler solution:
$(function(){
$(".toggle_container").hide();
$("li.trigger").click(function(){
$(".toggle_container").not($(this).next()).hide();
$(this).addClass("active").next(".toggle_container").slideToggle("slow")
.end().siblings().removeClass("active");
});
});
Note that the only thing needed to fix the source code is to exclude the hidden item you want to hide, so the toggle works correctly (it was always hidden before the toggle, so the toggle was always "show"), you do this by adding the .not()
following way:
$(".toggle_container").hide();
$(".toggle_container").not($(this).next()).hide();
a source to share