Dave Dave - 1 year ago 90
jQuery Question

Have some buggy jquery code when hiding and showing a div

Ive obviously got a little bit of this code wrong but not sure where? So when i click .link it toggles correctly, but when i click on the li it freaks out hides the toggle and wont let click .link again the show?

$(function() {
$('.link').click(function(event){
event.preventDefault();
$('#link' + $(this).attr('id')).toggle();
});
});


Here is my partial html for example

<li class="link" id="3"> <%= link_to "Kids" %></li>
<ul class="sub-link" id="link3">
<li> <%= link_to "Tops" %></li>
<li> <%= link_to "Trousers" %></li>
<li> <%= link_to "Shoes" %></li>
<li> <%= link_to "Coats" %></li>
</ul>
</ul>


or if any of you lovely gentlemen/women have a better way to perform this im all ears. (ps. im currently learning jquery)

thanks

Answer Source

Make sure to fix your HTML to something like this example. Not sure about your links (<%= link_to "Tops" %>) I've replaced them with <a> tags. Then of course you can go crazy in the javascript world and using id-numbers to find the other element. But if all you want to do is toggle the next element. Then don't overcomplicate things.

$(function() {
    $('.link').click(function(event){
        event.preventDefault();
        $(this).children('ul').toggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="link" id="3">
  <a href="#">Kids</a>
  <ul class="sub-link" id="link3">
    <li><a href="#">Tops</a> </li>
    <li><a href="#">Trousers</a></li>
    <li><a href="#">Shoes</a> </li>
    <li><a href="#">Coats</a> </li>
  </ul>
</li><!-- see this closing </li> where it is and know where it comes from! -->

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download