Jimmy Page Jimmy Page - 6 months ago 17
Javascript Question

Adding jQuery slideToggle() to oncliked event on anchor link

I have searched the whole web and I didn't manage to find a solution to my problem. I have some anchor links, in a fixed header, like this:

<ul>
<li class="dropdown">
<a href="#" class="dropbtn">Tab1</a>
<div class="dropdown-content">
<a href="#s1">link1</a>
<a href="#s2">link2</a>
</div>
</li>
<li class="dropdown">
<a href="#" class="dropbtn">Tab2</a>
<div class="dropdown-content">
<a href="#s3">link3</a>
<a href="#s4">link4</a>
</div>
</li>
<li class="dropdown">
<a href="#" class="dropbtn">Tab3</a>
<div class="dropdown-content">
<a href="#s5">link5</a>
<a href="#s6">link6</a>
<a href="#s7">link7</a>
</div>
</li>
<li class="dropdown">
<a href="#" class="dropbtn">Tab4</a>
<div class="dropdown-content">
<a href="#s8">link8</a>
<a href="#s9">link9</a>
<a href="#s0">link10</a>
</div>
</li>
</ul>


In my application, all these sections are hidden (
.content{display:none;}
, with
content
as the class of the tables). For example:

<div class="content">
<p>I am a section.</p>
<div style="overflow-x:auto;">
<table class="normal" id="s1">*data*</table>
</div>
</div>


Now, I'd like to
slideToggle()
the selected table (with the anchor link) in order to show it, and hide any previously "slided" table. I've tried a lot of jQuery codes, but none worked. What event/function may I have to add to onclick event of these anchor links?

Answer

You can do this quite simply in jQuery by using seperate counts of slideUp() and slideDown() instead of slideToggle().

I've replicated your environment in a fiddle and dropped the code in, here is the fiddle: https://jsfiddle.net/wo9n0yLt/

The code is below:

$('.menu > li > a').click(function() {
  var tab = $(this).attr('href');
  $('table').each(function() {
    $(this).slideUp();
  });
  $(tab).slideDown();
});
table {
  display: none;
  padding: 1em;
  border: 1px solid red;
}
<h2>
  My Menu Toggler
</h2>
<ul class="menu">
  <li><a href="#tab1">One</a></li>
  <li><a href="#tab2">Two</a></li>
  <li><a href="#tab3">Three</a></li>
</ul>
<table id="tab1">
  <tr>
    <td>TABLE 1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>
<table id="tab2">
  <tr>
    <td>TABLE 2</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>
<table id="tab3">
  <tr>
    <td>TABLE 3</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>

Comments