TriSTaR TriSTaR - 6 months ago 30
Javascript Question

Open the category when clicking

How to make to open the category when clicking and closed back.

enter image description here

I found one tutorial (http://plnkr.co/edit/ReNCjeCN8qwxI58RaMRd?p=preview), but when clicked it displays only the first link. How to make each item appear exactly as in the menu?

Code :

<!DOCTYPE HTML>
<html>
<head>
<meta charset="windows-1251">
<title>Выпадающий текст при нажатии на ссылку с помощью jQuery</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
$(".link").click(function() {
$("this").find(".nested_menu").slideToggle("slow");
$(this).toggleClass("active"); return false;
});
</script>
<style>
.nasted_menu {
display: none;
padding: 5px;
width: 400px;
height: 200px;
background: #09F;
color: #FFF;
}
.link {
background: #CCC;
color: #06F;
}
.active {
background: #FF9;
}
</style>
</head>
<body>
<ul>
<li class="link">Link1
<ul class="nested_menu">
<li>Nested point</li>
</ul>
</li>
<li class="link">Link2
...
</li>
</ul>
</body>
</html>

Answer

$(function() {
  $(".btn-slide").click(function() {
    $(this).next("#panel").slideToggle("slow");//use $(this) to get the clicked btnslide
    $(this).toggleClass("active");
    return false;
  });
});
#panel {
  display: none;
  padding: 5px;
  width: 400px;
  height: 200px;
  background: #09F;
  color: #FFF;
}
.btn-slide {
  background: #CCC;
  color: #06F;
}
.active {
  background: #FF9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" class="btn-slide">Click Me</a>
<div id="panel">
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex
  ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue
  duis dolore te feugait nulla facilisi.
</div>
<br>
<br>
<br>
<a href="" class="btn-slide">Click Me 2</a>
<div id="panel">
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
</div>
<br>
<br>
<br>
<a href="" class="btn-slide">Click Me 3</a>
<div id="panel">
  at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
</div>

  1. Use $(this) to get the clicked btnslide
  2. Use .next() to get the content of the clicked btnslide