-1

I've 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 won't let click .link again 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 you have a better way to perform this I'm all ears (I'm currently learning jQuery).

halfer
  • 19,824
  • 17
  • 99
  • 186
Dave
  • 313
  • 1
  • 3
  • 16
  • 5
    The markup is invalid – Andreas Oct 02 '17 at 14:40
  • 2
    https://stackoverflow.com/questions/5899337/proper-way-to-make-html-nested-list – bassxzero Oct 02 '17 at 14:41
  • can you clarify what you mean by "link?" Because it seems like the link and '.link' are the same thing. – Wold Oct 02 '17 at 14:44
  • Maybe you could change the approach to (in the function): `$(event.target).find('.sub-link').toggle()` (Not sure if feasible in your case, that's why I posted it here, and not in answer) – niorad Oct 02 '17 at 14:44
  • Wold, added the "." sorry about that – Dave Oct 02 '17 at 14:48
  • I am still confused by your phrasing. What is the difference between the ".link" and the "li", aren't the the same thing? Also, as pointed out, the markup is invalid, so maybe if you could show more of the html for context, it would help diagnose the problem. – Wold Oct 02 '17 at 14:55

1 Answers1

1

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! -->
caramba
  • 21,963
  • 19
  • 86
  • 127